package com.lenovo.leos.filebrowser.ui;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

import org.json.JSONException;
import org.xmlpull.v1.XmlPullParserException;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.Activity.OnTitleIconClickListener;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.DialogInterface.OnDismissListener;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.XmlResourceParser;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.os.StatFs;
import android.provider.MediaStore;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;

import com.lenovo.leos.filebrowser.R;
import com.lenovo.leos.filebrowser.engine.operation.FileDelete;
import com.lenovo.leos.filebrowser.engine.operation.FileOp;
import com.lenovo.leos.filebrowser.engine.operation.FileRename;
import com.lenovo.leos.filebrowser.engine.operation.FileShare;
import com.lenovo.leos.filebrowser.engine.util.DirDefines;
import com.lenovo.leos.filebrowser.engine.util.FileClipBoard;
import com.lenovo.leos.filebrowser.engine.util.FileHandler;
import com.lenovo.leos.filebrowser.engine.util.FileUtil;
import com.lenovo.leos.filebrowser.engine.util.HzToPy;
import com.lenovo.leos.filebrowser.engine.util.MimeTypeParser;
import com.lenovo.leos.filebrowser.engine.util.MimeTypes;
import com.lenovo.leos.filebrowser.engine.util.FileHandler.MsgHandleFunc;
import com.lenovo.leos.filebrowser.netdisk.ErrorMessageDialog;
import com.lenovo.leos.filebrowser.netdisk.LoadedData;
import com.lenovo.leos.filebrowser.netdisk.NetDiskConstant;
import com.lenovo.leos.filebrowser.netdisk.NetDiskManager;
import com.lenovo.leos.filebrowser.netdisk.NetDiskOpResult;
import com.lenovo.leos.filebrowser.netdisk.NetFile;
import com.lenovo.leos.filebrowser.netdisk.ProgressMessageDialog;
import com.lenovo.leos.filebrowser.ui.IconifiedTextListAdapter.ViewHolder;
import com.lenovo.leos.internal.filemanager.Filemanager;
import com.lenovo.leos.letools.db.FileDownloadEntity;
import com.lenovo.leos.letools.db.FileDownloadService;
import com.lenovo.leos.letools.db.FileUploadEntity;
import com.lenovo.leos.letools.db.FileUploadService;
import com.lenovo.leos.letools.lenovodata.DownLoadServer;
import com.lenovo.leos.letools.lenovodata.UploadServer;

public class FileBrowser extends BaseActivity implements
		OnTitleIconClickListener, OnClickListener, OnTouchListener {

	private static final String TAG = "FileBrowserActivity";
	private DownLoadServer downloadServer;
	private UploadServer uploadServer;
	
	private class LoginHandler extends Handler {
		public LoginHandler(Looper looper) {
			super(looper);
		}

		@Override
		public void handleMessage(Message msg) {
			Log.e(TAG, "==> handleMessage");

			if (msg.what == MSG_LOGIN_OK) {
				ProgressMessageDialog.cancelDialog();
				Intent intent = new Intent();
				if (isUpload) {
					String mUpload = DirDefines.UPLOAD;
					mUpload = DirDefines.UPLOAD;
					intent.putExtra("mUpload", mUpload);
					intent.putExtra("uploadFile", uploadFile);
					intent.putExtra("uploadFileTypes", uploadFileTypes);
					if (TAG_FLAG) {
						Log.d(TAG, "the uploadFile[0] is ================ "
								+ uploadFile[0]);
						Log.d(TAG,
								"the uploadFileTypes[0] is ================ "
										+ uploadFileTypes[0]);
					}
					intent.setClass(
							FileBrowser.this,
							com.lenovo.leos.filebrowser.netdisk.LenovoInterfaceActivity.class);
					intent.putExtra("projectState", projectState);
					startActivity(intent);
					if (null != mndManager) {
						mndManager.unbindOpService();
						mndManager = null;
					}
				} else {
					intent.setClass(
							FileBrowser.this,
							com.lenovo.leos.filebrowser.netdisk.LenovoActivity.class);
					intent.putExtra("projectState", projectState);
					startActivity(intent);
					if (null != mndManager) {
						mndManager.unbindOpService();
						mndManager = null;
					}
					finish();
				}

			} else if (msg.what == MSG_LOGIN_FAILED) {
				ProgressMessageDialog.cancelDialog();
				if (null != mndManager) {
					mndManager.unbindOpService();
					mndManager = null;
				}
				Toast.makeText(FileBrowser.this, "login net disk failed",
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	private class LoginThread extends Thread {

		Context mContext;
		boolean mStop = false;
		protected PowerManager.WakeLock mWakeLock;

		public LoginThread(Context context) {
			mContext = context;
			threadInt();
		}

		private void threadInt() {
			PowerManager powerManager = (PowerManager) mContext
					.getSystemService(Context.POWER_SERVICE);
			mWakeLock = powerManager.newWakeLock(
					PowerManager.SCREEN_DIM_WAKE_LOCK
							| PowerManager.ON_AFTER_RELEASE, TAG);
		}

		public void toStop() {
			mStop = true;
		}

		public void onLoginOk() {
			Message msg = mHandler.obtainMessage(MSG_LOGIN_OK, 0, 0, null);
			mHandler.sendMessage(msg);
		}

		public void onLoginFailed() {
			Message msg = mHandler.obtainMessage(MSG_LOGIN_FAILED, 0, 0, null);
			mHandler.sendMessage(msg);
		}
	}

	private class Position {
		private static final String TAG = "Postion";

		private File mfDir = null;
		private int miIndex = 0;

		public Position(int index, File file) {
			if (0 > index || null == file || !file.isDirectory()) {
				Log.e(TAG, "invalid parameter in Position");
				return;
			}
			miIndex = index;
			mfDir = file;
		}

		public void setIndex(int index) {
			if (0 > index) {
				Log.e(TAG, "invalid index in setIndex");
				return;
			} else
				miIndex = index;
		}

		public int getIndex() {
			return miIndex;
		}

		public void setDir(File file) {
			if (null == file || !file.isDirectory()) {
				Log.e(TAG, "invalid parameter in setPosY");
				return;
			} else
				mfDir = file;
		}

		public File getDir() {
			return mfDir;
		}

		public void dump() {
			Log.d(TAG, "===== Position Object Content =====");
			Log.d(TAG, "the index is: " + String.valueOf(miIndex));
			Log.d(TAG, "the dir is: " + mfDir.getAbsolutePath());
			Log.d(TAG, "===================================");
		}
	};

	private boolean pageFlag = false;
	private boolean updateFlag = false; // add 2010-11-27 by xie
	private boolean openFlag = false; // add 2010-11-27 by xie
	private boolean menuFlag = false; // add 2010-12-13 by xie
	private File refreshFile = null; // add 2011-01-10 by xie
	private static final String ZIP_MIMETYPE = "compressor/zip";// add xieqm
																// 110112

	private enum DISPLAYMODE {
		ABSOLUTE, RELATIVE
	};

	public final static int _LIST = 10;
	public final static int _SELECT = 11;

	protected final int SUB_ACTIVITY_REQUEST_CODE = 1337;
	// private final String root = Constant.root;
	private final String root = DirDefines.mDir1;// Constant.sdroot;
	// private final String localroot = Constant.localroot;
	private final String sdroot = DirDefines.mDir1;// Constant.sdroot;
	// private final String uroot = Constant.uroot;
	private final String ZIPENDSTRING = ".zip";
	// private enum LOCATION{LOCAL,SDCARD,UDISK};
	// private LOCATION location = LOCATION.LOCAL;
	public static boolean isUDiskMnt = false;

	private final DISPLAYMODE displayMode = DISPLAYMODE.RELATIVE;

	/** Contains directories and files together */
	private List<IconifiedText> directoryEntries = new ArrayList<IconifiedText>();
	/** Dir separate for sorting */
	List<IconifiedText> mListDir = new ArrayList<IconifiedText>();
	/** Files separate for sorting */
	List<IconifiedText> mListFile = new ArrayList<IconifiedText>();
	/** SysDir separate for sorting */
	List<IconifiedText> mListSys = new ArrayList<IconifiedText>();

	private File currentDirectory = new File(sdroot);

	// a list contains all selected file objects;
	public static List<File> MarkedFile = new ArrayList<File>();
	// flag to identify whether some files are selected.
	// The activities of operation menu items(delete,cut,copy,compress) are
	// depends on isSelected
	public static boolean isSelected = false;
	// flag to identify cut or copy operation.
	// The activities of operation menu item(paste) are depends on cut_copy
	public static boolean cut_copy = false;

	private static LinkedList<Position> sllPos = new LinkedList<Position>();

	public enum OPTYPE {
		CUT, COPY
	};

	public static OPTYPE opType;
	// the state of the progress in.
	public static int State;

	// define menu options ID
	private static final int SELECT_ID = Menu.FIRST;
	private static final int PASTE_ID = Menu.FIRST + 1;
	private static final int NEW_ID = Menu.FIRST + 2;

	private static final int DEL_ID = Menu.FIRST + 3;
	private static final int CUT_ID = Menu.FIRST + 4;
	private static final int COPY_ID = Menu.FIRST + 5;
	private static final int COMPRESS_ID = Menu.FIRST + 6;

	private static final int RENAME_ID = Menu.FIRST + 7;
	private static final int DECOMPRESS_ID = Menu.FIRST + 8;
	private static final int ATTRIDIS_ID = Menu.FIRST + 9;
	private static final int SEND_ID = Menu.FIRST + 10;
	private static final int MNT_ID = Menu.FIRST + 11;
	private static final int PRE_UPLOAD = Menu.FIRST + 12;
	// private static final int UNMNT_ID =Menu.FIRST+12;
	// private static final int EXIT_ID =Menu.FIRST+13;

	IconifiedTextListAdapter itemList;
	// IconifiedTextListAdapter itemSelect;
	// define UI components
	// private ImageButton imbtnBack;
	private Button btnSearch;
	// private TabButtonTop btnLocal;
	private Button btnSD;
	// private TabButtonTop btnUdisk;
	private EditText editText;
	public static Button btnSelectAll;// modified by PH 091024
	public static Button btnCancleAll;// modified by PH 091024
	private TextView tv = null;
	// private Button btnFinish;
	// add by PH 091011
	private static MimeTypes mMimeTypes = null;
	// end PH 091011
	// add by PH 091012
	public static final String ACTION_PICK_DIRECTORY = "org.openintents.action.PICK_DIRECTORY";
	// end PH 091012
	// add by PH 091013
	public static int officeFlag;
	String mInitDefaultPath;
	// end PH 091013
	boolean openfile = false;

	private static boolean nothing = false;
	// add by PH 091024
	private static final int FILE_NAME_NUM_MAX = 85;
	private static final int OFFICE_FILE_NAME_NUM_MAX = 81;

	boolean mToCloseSend = false;
	private boolean mRegisterReceiver = false;
	File searchFile;
	boolean search = false;
	boolean searchDecom = false;
	String searchpath;
	String searchpathnofile;
	// private boolean mChecked = false;
	InputMethodManager inputMethodManager;
	private boolean sdRemoved = false;
	// int length;
	// private ContentResolver mResolver = null;
	private File[] mFilesOnCurDir;
	private ProgressDialog mProgressDialog;
	private MyBrowseToThread mBrowseToThread = null;
	private MyAttributeThread mAttributeThread = null;
	MyBrowserToHandler mEH = null;
	private static final int BROWSETO_RESULT_MSG = 40000;
	private static final int ATTRIBUTE_RESULT_MSG = 50000;
	boolean browsetoThreadFlag = false;
	boolean SdcardUnmounted = false;
	TextView t;
	boolean init = false;
	boolean mBrowseToThreadStop = false;
	private int subDirNum = 0;
	private int fileNum = 0;
	private long fileSize = 0;
	String arrfilename;
	String arrsubdir;
	String arrfilenum;
	String arrtotalfileSize;
	String arrmodifyDate;
	// View mtextEntryView;
	TextView mSubFile;
	TextView mTotalSize;
	TextView mSubDir;
	ListView mlvContent;

	private Position mpstCur = null;

	// add by xieqm 110225
	private static final boolean TAG_FLAG = false;
	private static final int SWITCHING_DIRECTORY = Menu.FIRST + 12;
	private static String projectState;
	private static FileBrowser instance = new FileBrowser();
	private static final String OPEN_SAVE = "android.intent.action.OPEN_SAVE_DIALOG";
	private static final int LENOVO_MODE_SAVE_FILE = 3;
	private AlertDialog dialog;
	private TextView sdcardText;
	private static final int MODE_SELECT_PATH = 1;
	private boolean mReceiver = false;
	private String sdCardtatus = Environment.getExternalStorageState();
	private LinearLayout layout, phoneLayout, sdcardLayout, lenovoLayout;
	private String[] uploadFile;
	private boolean[] uploadFileTypes;

	private static final int MSG_LOGIN_OK = 100000;
	private static final int MSG_LOGIN_FAILED = 100001;
	private static boolean isUpload;
	private List<LoadedData> upAndDownList = new ArrayList<LoadedData>();
	public static final String LIST_NULL = "@@@##$$%%%%^^^&&&***";

	NetDiskManager mndManager = null;
	LoginHandler mHandler = new LoginHandler(Looper.myLooper());

	long mlCurOp = -1;

	public static FileBrowser getInstance() {
		return instance;
	}

	// end

	private class MyBrowserToHandler extends Handler {
		public MyBrowserToHandler(Looper looper) {
			super(looper);
		}

		@Override
		public void handleMessage(Message msg) {
			if (msg.what == BROWSETO_RESULT_MSG) {
				// if (State == Constant._LIST) {

				itemList.setListItems(directoryEntries);
				mlvContent.setAdapter(itemList);

				if (directoryEntries.size() == 0) {
					nothing = true;
					t.setText(R.string.not_found);
					t.setVisibility(View.VISIBLE);
				} else {
					nothing = false;
					t.setVisibility(View.GONE);

					if (null != mpstCur) {
						File dir = mpstCur.getDir();
						if (dir.equals(currentDirectory)) {
							mlvContent.setSelection(mpstCur.getIndex());
						} else {
							mlvContent.setSelection(0);
						}
					} else {
						mlvContent.setSelection(0);
					}
				}

				// } else if (State == Constant._SELECT) {
				/*
				 * itemSelect.setListItems(directoryEntries);
				 * if(getListAdapter() != itemSelect){
				 * setListAdapter(itemSelect); }else{
				 * itemSelect.notifyDataSetChanged(); } }
				 */

				browsetoThreadFlag = false;
			} else if (msg.what == ATTRIBUTE_RESULT_MSG) {
				arrtotalfileSize = transferSize(fileSize);
				mSubFile.setText(getResources().getString(R.string.filenum)
						+ fileNum);
				mTotalSize.setText(getResources().getString(R.string.totalsize)
						+ arrtotalfileSize);
				mSubDir.setText(getResources().getString(R.string.subdir)
						+ subDirNum);
			}
		}

	}

	private void initData() {
		if (null == sllPos) {
			sllPos = new LinkedList<Position>();
		} else
			sllPos.clear();
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		// add by xieqm 110225
		projectState = getIntent().getStringExtra("projectState");
		if (TAG_FLAG) {
			Log.d(TAG, "state=======================" + projectState);
		}
		// end
		// add 2010-12-07 by xqm
		IntentFilter commandFilter = new IntentFilter();
		commandFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
		commandFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
		commandFilter.addAction(Intent.ACTION_MEDIA_REMOVED);
		commandFilter.addAction(Intent.ACTION_MEDIA_SHARED);
		commandFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTABLE);
		commandFilter.addAction(Intent.ACTION_MEDIA_CHECKING);
		commandFilter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
		commandFilter.addAction(Intent.ACTION_MEDIA_NOFS);
		commandFilter.addDataScheme("file");
		registerReceiver(SdCardIntentReceiver, commandFilter);
		mRegisterReceiver = true;
		// end
		inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

		initData();

		State = _LIST;
		MarkedFile.clear();

		String status = Environment.getExternalStorageState();
		if (TAG_FLAG)
			Log.d(TAG, "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@  onCreate status="
					+ status + " @@@@@@@@@@@@@@@@@@@@@@@@");
		if (status.equals("noinsert")) {// add 2010-12-07 by xie "noinsert"
			initState();// add 2010-12-07 by xqm
			btnSD.setVisibility(View.GONE);
			btnSearch.setVisibility(View.GONE);
			editText.setVisibility(View.GONE);
			tv.setVisibility(View.GONE);
			t.setVisibility(View.VISIBLE);
			mlvContent.setVisibility(View.GONE);
			t.setText(R.string.sd_removed);
		} else if (status.equals(Environment.MEDIA_SHARED)) {
			initState();
			btnSD.setVisibility(View.GONE);
			btnSearch.setVisibility(View.GONE);
			editText.setVisibility(View.GONE);
			tv.setVisibility(View.GONE);
			t.setVisibility(View.VISIBLE);
			mlvContent.setVisibility(View.GONE);
			t.setText(R.string.sd_shared);
			menuFlag = false;// add 2010-12-13 by xqm
		} else if (status.equals(Environment.MEDIA_UNMOUNTED)) { // add
																	// 2010-12-08
																	// by xqm
																	// "unmounted"
			initState();
			btnSD.setVisibility(View.GONE);
			btnSearch.setVisibility(View.GONE);
			editText.setVisibility(View.GONE);
			tv.setVisibility(View.GONE);
			t.setVisibility(View.VISIBLE);
			mlvContent.setVisibility(View.GONE);
			t.setText(R.string.sd_unmounted);
		} else if (status.equals(Environment.MEDIA_CHECKING)) { // add
																// 2010-12-14 by
																// xqm
																// "checking"
			initState();
			btnSD.setVisibility(View.GONE);
			btnSearch.setVisibility(View.GONE);
			editText.setVisibility(View.GONE);
			tv.setVisibility(View.GONE);
			t.setVisibility(View.VISIBLE);
			mlvContent.setVisibility(View.GONE);
			t.setText(R.string.sd_disk_checking);
		} else if (status.equals(Environment.MEDIA_MOUNTED)
				|| status.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
			menuFlag = true; // add 2010-12-13 by xqm
			getWindow().addFlags(
					WindowManager.LayoutParams.FLAG_ROCKET_MENU_NOTIFY);
			itemList = new IconifiedTextListAdapter(this, this.directoryEntries);
			// itemSelect = new
			// IconifiedTextListAdapter(this,this.directoryEntries);

			mEH = new MyBrowserToHandler(Looper.myLooper());
			this.customTitleIcon(0, 0, 0, this);
			cut_copy = false;
			// Create system directory under localroot if which do not exist.
			// add by PH 091011
			initMimeTypes();
			// end PH 091011
			initState();
			Intent myintent = getIntent();
			mInitDefaultPath = myintent.getStringExtra("INIT_DEFAULT_PATH");
			browseToRoot();
			mlvContent.setSelection(0);
		} else {
			init = true;
			Intent myintent = getIntent();
			if (myintent.getStringExtra("INIT_DEFAULT_PATH") != null) {
				finish();
			}
			itemList = new IconifiedTextListAdapter(this, this.directoryEntries);
			// itemSelect = new
			// IconifiedTextListAdapter(this,this.directoryEntries);
			mEH = new MyBrowserToHandler(Looper.myLooper());
			this.customTitleIcon(0, 0, 0, this);
			// this.customTitleIcon(0, 0, 0, this);
			cut_copy = false;

			initMimeTypes();
			// browseToRoot();
			// mlvContent.setSelection(0);
		}
		
		downloadServer = DownLoadServer.getInstance(this);
		uploadServer = UploadServer.getInstance(this);
	}

	@Override
	protected void onResume() {
		if (TAG_FLAG) {
			Log.i(TAG, "==> onResume");
			Log.i(TAG, "the updateFlag is " + updateFlag);
			Log.i(TAG, "the openFlag is " + openFlag);
		}
		super.onResume();
		if (pageFlag) {
			if (TAG_FLAG)
				Log.d(TAG, "onResume===========" + pageFlag);
			initDatas();
		} else {
			sllPos.poll();
		}
		isUpload = false;
	}

	/*
	 * add 2010-11-26 by xie
	 */
	private void initDatas() {
		State = _LIST;
		initState();
		String status = Environment.getExternalStorageState();
		if (TAG_FLAG)
			Log.i(TAG, "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@  onResume status="
					+ status + " @@@@@@@@@@@@@@@@@@@@@@@@");
		if (status.equals(Environment.MEDIA_MOUNTED)
				|| status.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
			// initState();
			getWindow().addFlags(
					WindowManager.LayoutParams.FLAG_ROCKET_MENU_NOTIFY);
			mlvContent.setVisibility(View.VISIBLE);
			btnSD.setVisibility(View.VISIBLE);
			btnSearch.setVisibility(View.VISIBLE);
			editText.setVisibility(View.VISIBLE);
			tv.setVisibility(View.VISIBLE);
			sdRemoved = false;
			browseTo(currentDirectory);
		} else {// end
			sdRemoved = true;

			final TextView t = (TextView) findViewById(R.id.empty);
			if (status.equals(Environment.MEDIA_REMOVED)) {
				t.setText(R.string.sd_removed);
			} else if (status.equals(Environment.MEDIA_UNMOUNTED)) {
				t.setText(R.string.sd_unmounted);
			} else if (status.equals(Environment.MEDIA_SHARED)) {
				t.setText(R.string.sd_shared);
			} else if (status.equals(Environment.MEDIA_BAD_REMOVAL)) {
				t.setText(R.string.sd_bad_removal);
			} else if (status.equals(Environment.MEDIA_NOFS)) {
				t.setText(R.string.sd_nofs);
			} else if (status.equals(Environment.MEDIA_CHECKING)) {
				t.setText(R.string.sd_disk_checking);
			} else if (status.equals(Environment.MEDIA_UNMOUNTABLE)) {
				t.setText(R.string.sd_corrupted);
			}

			mlvContent.setVisibility(View.GONE);
			t.setVisibility(View.VISIBLE);
			btnSD.setVisibility(View.GONE);
			btnSearch.setVisibility(View.GONE);
			editText.setVisibility(View.GONE);
			tv.setVisibility(View.GONE);
		}
	}

	@Override
	protected void onRestart() {
		if (TAG_FLAG)
			Log.i(TAG, "==> onRestart");
		super.onRestart();
		// add by xieqm 110309
		boolean searchPaste = CutAndCopyVo.getInstance().isSearchPaste();
		if (searchPaste == true) {
			MarkedFile.clear();
			MarkedFile = CutAndCopyVo.getInstance().getCutFile();
			cut_copy = CutAndCopyVo.getInstance().isCut_copy();
		}
		CutAndCopyVo.getInstance().setSearchPaste(false);
		// end
		if (openFlag) {
			if (TAG_FLAG)
				Log.d(TAG, "********openFlag************" + openFlag);
			// updage 83169 2011-01-10 by xieqm
			if (refreshFile != null && !refreshFile.exists()) {
				initDatas();
				refreshFile = null;
			}
			// end
			pageFlag = false;
		} else {
			initDatas();
		}
		if (TAG_FLAG)
			Log.d(TAG, "*************onRestart**************" + pageFlag);
	}

	@Override
	protected void onPause() {
		if (TAG_FLAG) {
			Log.i(TAG, "==> onPause");
			Log.i(TAG, "the updateFlag is " + updateFlag);
			Log.i(TAG, "the openFlag is " + openFlag);
		}
		super.onPause();
		if (updateFlag) {
			if (TAG_FLAG)
				Log.d(TAG, "********updateFlag************" + updateFlag);
			pageFlag = true;
			updateFlag = false;
		} else {
			pageFlag = false;
		}
		// flag = true;
		if (TAG_FLAG)
			Log.d(TAG, "*************onPause**************" + pageFlag);
	}

	@Override
	protected void onStart() {
		if (TAG_FLAG)
			Log.i(TAG, "==> onStart");
		super.onStart();
		pageFlag = false;
		if (TAG_FLAG)
			Log.d(TAG, "*************onStart**************" + pageFlag);
	}

	@Override
	protected void onStop() {
		if (TAG_FLAG)
			Log.i(TAG, "==> onStop");
		super.onStop();
		pageFlag = true;
		if (TAG_FLAG)
			Log.d(TAG, "*************onStop**************" + pageFlag);
	}

	// end

	@Override
	protected void onDestroy() {
		if (TAG_FLAG)
			Log.i(TAG, "==> onDestroy");
		super.onDestroy();
		if (mRegisterReceiver) {
			unregisterReceiver(SdCardIntentReceiver);
			if (TAG_FLAG)
				Log.i(TAG, "*********OnDestroy unregisterReceiver *********");
		}
		if (browsetoThreadFlag) {
			if (mProgressDialog != null) {
				mProgressDialog.dismiss();
				mProgressDialog = null;
			}
		}
		if (mAttributeThread != null)
			mAttributeThread = null;
		if (mReceiver) {
			unregisterReceiver(sdCardIntentReceiver);
			Log.i(TAG, "*********OnDestroy unregisterReceiver *********");
		}

		if (null != dialog) {
			dialog.cancel();
		}

		if (null != mndManager) {
			mndManager.unbindOpService();
			mndManager = null;
		}

		isUpload = false;

		// add by xieqm 110309
		CutAndCopyVo.getInstance().setCut_copy(false);
		CutAndCopyVo.getInstance().setCutFile(null);
		// end

	}

	private void initState() {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%initState");
		switch (State) {
		case _LIST:
			// set the layout for List state
			setContentView(R.layout.main);
			setTitle(R.string.apptitle);
			// get elements for List state by id
			editText = (EditText) findViewById(R.id.searchEdit);
			btnSearch = (Button) findViewById(R.id.search);
			btnSD = (Button) findViewById(R.id.btnsd);
			t = (TextView) findViewById(R.id.empty);

			/*
			 * update 2010-11-27 by xie
			 */
			if (currentDirectory.getAbsolutePath().equals(DirDefines.mDir1)) {// Constant.sdroot
				btnSD.setEnabled(false);
			}

			tv = (TextView) findViewById(R.id.tv);
			setLocationText(currentDirectory.getAbsolutePath());
			btnSearch.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					inputMethodManager.hideSoftInputFromWindow(
							mlvContent.getWindowToken(), 0);

					Intent intent = new Intent();
					intent.putExtra("projectState", projectState);// add by
																	// xieqm
																	// 110307
					intent.setClass(FileBrowser.this, FileSearcher.class);
					Bundle bundle = new Bundle();
					bundle.putString("path", currentDirectory.getAbsolutePath());// add
																					// by
																					// PH
					// 091114
					if (isNameUseable(editText.getText().toString().trim(),
							false)) {
						intent.putExtra("searchStr", editText.getText()
								.toString());
						intent.putExtras(bundle);
						startActivityForResult(intent, Constant._SEARCH);
					} else if (editText.getText().length() == 0) {
						Toast.makeText(FileBrowser.this, R.string.edithint,
								Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(FileBrowser.this, R.string.namebad,
								Toast.LENGTH_SHORT).show();
					}
					editText.setText("");
				}
			});

			btnSD.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					browseToRoot();
				}
			});

			mlvContent = (ListView) findViewById(android.R.id.list);
			mlvContent.setAdapter(itemList);
			break;
		case _SELECT:
			if (!MarkedFile.isEmpty()) {
				MarkedFile.clear();
				isSelected = false;
			}
			setContentView(R.layout.main_select);
			setTitle(R.string.apptitle);

			btnSelectAll = (Button) findViewById(R.id.btnselectall);
			btnCancleAll = (Button) findViewById(R.id.btncancleall);
			btnCancleAll.setEnabled(false);
			btnSelectAll.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					markAllFile();
					// add by PH 091024
					btnCancleAll.setEnabled(true);
					btnSelectAll.setEnabled(false);
					// end PH 091024
				}
			});
			btnCancleAll.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					// check all files in current directory
					unmarkallFile();
					// add by PH 091024
					btnCancleAll.setEnabled(false);
					btnSelectAll.setEnabled(true);
					// add by PH 091024
				}
			});
			mlvContent = (ListView) findViewById(android.R.id.list);
			mlvContent.setAdapter(itemList);
			break;
		}
		// register a ContextMenu for the current listview
		mlvContent.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				if (State == _LIST) {
					File clickedFile = null;
					switch (FileBrowser.this.displayMode) {
					case RELATIVE:
						clickedFile = new File(
								FileBrowser.this.currentDirectory
										.getAbsolutePath()
										+ "/"
										+ FileBrowser.this.directoryEntries
												.get((int) arg3).getText());
						if (TAG_FLAG) {
							Log.d(TAG,
									"the onItemClick isSelected is ============="
											+ isSelected);
							Log.d(TAG,
									"the onItemClick nothing is ================"
											+ nothing);
						}

						break;
					case ABSOLUTE:
						clickedFile = new File(
								FileBrowser.this.directoryEntries.get(
										(int) arg3).getText());
						break;
					}
					if (clickedFile != null)
						if (clickedFile.isDirectory()) {
							if (State == _SELECT) {// add by PH 091102
								FileBrowser.this.MarkedFile.clear();
								isSelected = false; // add by PH 091113
							}
						}
					Position pos = new Position(mlvContent
							.getFirstVisiblePosition(), currentDirectory);
					if (TAG_FLAG) {
						Log.d(TAG,
								"the index is ===============" + pos.getIndex());
						Log.d(TAG, "the file is ===============" + clickedFile);
					}
					pos.dump();
					sllPos.addFirst(pos);
					mpstCur = null;
					// update 83169 2011-01-10 by xieqm
					refreshFile = clickedFile;
					// end
					FileBrowser.this.browseTo(clickedFile);
				} else {
					ViewHolder cache = (ViewHolder) arg1.getTag();
					if (TAG_FLAG)
						Log.d(TAG, "FileBrowser========================"
								+ cache.checkbox);
					cache.checkbox.setChecked(!cache.checkbox.isChecked());
				}
			}

		});

		registerForContextMenu(mlvContent);
	}

	/**
	 * This function browses to the root-directory of the file-system.
	 */
	private void browseToRoot() {
		if (TAG_FLAG)
			Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%browseRoot");
		if (this.mInitDefaultPath != null) {
			File file = new File(mInitDefaultPath);
			if (file.isDirectory()) {
				browseTo(file);
			} else {
				file = new File(file.getParent());
				if (file.isDirectory()) {
					browseTo(file);
				}
			}
			mInitDefaultPath = null;
			return;
		} else {
			browseTo(new File(sdroot));
		}
	}

	/**
	 * This function browses up one level according to the field:
	 * currentDirectory
	 */
	private void upOneLevel() {
		if (TAG_FLAG)
			Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%upOneLevel");
		String parent = this.currentDirectory.getParent();
		if (parent != null) {
			if (parent.equals(root)) {
				parent = sdroot;
			}
			mpstCur = sllPos.poll();
			this.browseTo(new File(parent));
		}
	}

	private class MyBrowseToThread extends Thread {

		Context mContext;
		boolean mStop = false;
		protected PowerManager.WakeLock mWakeLock;

		public MyBrowseToThread(Context context) {
			// mStop = false;
			mContext = context;
			threadInt();
		}

		private void threadInt() {
			PowerManager powerManager = (PowerManager) mContext
					.getSystemService(Context.POWER_SERVICE);
			mWakeLock = powerManager.newWakeLock(
					PowerManager.SCREEN_DIM_WAKE_LOCK
							| PowerManager.ON_AFTER_RELEASE, TAG);
		}

		public void toStop() {
			// mResume = true;
			mStop = true;
		}

		private void onBrowseToResult() {
			Message msg = mEH.obtainMessage(BROWSETO_RESULT_MSG, 0, 0, null);
			mEH.sendMessage(msg);
		}
	}

	private class MyAttributeThread extends Thread {
		Context mContext;
		boolean mStop = false;

		public MyAttributeThread(Context context) {
			mContext = context;
		}

		public void toStop() {
			mStop = true;
		}

		public void onAttributeResult() {
			Message msg = mEH.obtainMessage(ATTRIBUTE_RESULT_MSG, 0, 0, null);
			mEH.sendMessage(msg);
		}

	}

	private void browseTo(final File file) {
		if (TAG_FLAG) {
			Log.d(TAG, "==> browseTo");
			Log.d(TAG,
					"+++++++++++++++---------------------------"
							+ file.getAbsolutePath());
		}
		if (this.displayMode == DISPLAYMODE.RELATIVE) {
			Log.i(TAG, "DISPLAYMODE.RELATIVE");
			Log.i(TAG, "the state is " + State);
			// If file is a directory,call fill() and browse it.
			if (file.isDirectory()) {
				if (State == _LIST) {
					Log.i(TAG, "state is LIST");
					final File[] files = file.listFiles();
					if (mFilesOnCurDir != null
							&& mFilesOnCurDir.length == files.length) {

						Log.i(TAG, "check whether to changed");

						int i;
						for (i = 0; i < mFilesOnCurDir.length; i++) {
							if (mFilesOnCurDir[i].equals(files[i])) {
								if (TAG_FLAG)
									Log.d(TAG,
											"+++++++++++++++++++++++++++++"
													+ mFilesOnCurDir[i]
															.getAbsolutePath());
								continue;
							} else {
								break;
							}
						}
						if (i == mFilesOnCurDir.length) {
							if (TAG_FLAG)
								Log.d(TAG,
										"******************** equal file list ***********");
							sortedFileList(mFilesOnCurDir);// add by xieqm
															// 110310 for
															// reflash del
							return;
						}
					}

					Log.i(TAG, "get file content");
					mFilesOnCurDir = files;
					currentDirectory = file;
					if (files.length > 700) {
						browsetoThreadFlag = true;
						mProgressDialog = new ProgressDialog(FileBrowser.this);
						// mProgressDialog.setTitle(R.string.delete_file);
						mProgressDialog.setMessage(getString(R.string.waiting));
						mProgressDialog.setCancelable(false);
						// mProgresmlvContentsDialog.setDefaultButton(true);
						mProgressDialog.setButton(
								getText(R.string.alert_dialog_cancel),
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										// User clicked No so do some stuff
										if (mBrowseToThread != null)
											mBrowseToThread.toStop();
										// mBrowseToThread = null;
										mProgressDialog.dismiss();
									}

								});
						mProgressDialog
								.setOnDismissListener(new OnDismissListener() {
									public void onDismiss(DialogInterface arg0) {
										// TODO Auto-generated method stub
										if (mBrowseToThread != null)
											mBrowseToThread.toStop();
										// finish();
									}
								});
						mProgressDialog.show();
						mBrowseToThread = new MyBrowseToThread(this) {
							public void run() {
								if (TAG_FLAG)
									Log.d(TAG,
											"******************** not equal file list ***********");
								// fill(mFilesOnCurDir);
								// directoryEntries.clear();
								sortedFileList(mFilesOnCurDir);
								mBrowseToThread.onBrowseToResult();
								mProgressDialog.dismiss();
								mProgressDialog = null;
							}
						};
						mBrowseToThread.start();
					} else {
						browsetoThreadFlag = false;
						if (TAG_FLAG)
							Log.d(TAG,
									"******************** not equal file list ***********");
						// fill(mFilesOnCurDir);
						this.directoryEntries.clear();
						sortedFileList(mFilesOnCurDir);
					}
				}

				setLocationText(file.getPath());
			} else {
				FileManagerOpenFile(file, this);
			}
		}
		/*
		 * update 2010-11-26 by xie
		 */
		if (currentDirectory.getAbsolutePath().equals(DirDefines.mDir1))// Constant.sdroot
			btnSD.setEnabled(false);
		else
			btnSD.setEnabled(true);
	}

	private void setLocationText(String lt) {
		String relativePath = "";
		String[] strArr;
		String ln = "";
		String result = "";
		lt = Constant.textConvert(this, lt);
		relativePath = lt.replaceFirst(DirDefines.mDir1,
				getString(R.string.sdcard));// Constant.sdroot
		relativePath = relativePath.trim();
		strArr = TextUtils.split(relativePath, "/");
		for (int i = 1; i < strArr.length; i++) {
			ln += ">" + strArr[i];
		}
		result = getString(R.string.sdcard) + ln;

		// int index = result.lastIndexOf(">");
		// if (result.length() > 45) {
		// result = "......" + result.substring(index, result.length());
		tv.setText(result);
		// } else {
		// if (result.equals(getString(R.string.sdcard))) {
		// tv.setText(result + ">");
		// } else {
		// tv.setText(result);
		// }
		// }
	}

	// add by PH 091011
	private void initMimeTypes() {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%initMimeTypes");
		if (mMimeTypes == null) {
			MimeTypeParser mtp = new MimeTypeParser();

			// XmlResourceParser in = getResources().getXml(
			// com.android.internal.R.xml.mimetypes);
			XmlResourceParser in = getResources().getXml(R.xml.mimetypes);
			try {
				mMimeTypes = mtp.fromXmlResource(in);
			} catch (XmlPullParserException e) {
				if (TAG_FLAG)
					Log.e(TAG,
							"************************** XmlPullParserException",
							e);
				throw new RuntimeException(
						"*************************** XmlPullParserException");
			} catch (IOException e) {
				if (TAG_FLAG)
					Log.e(TAG, "************************** IOException", e);
				throw new RuntimeException(
						"************************** IOException", e);
			}
		}
	}

	/**
	 * call an activity to open a file according the file's type.
	 * 
	 * @param aFile
	 *            - file to open
	 */

	public void FileManagerOpenFile(final File aFile, final Context context) {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%FileManagerOpenFile");
		if (!aFile.exists()) {
			Toast.makeText(context,
					aFile + getString(R.string.error_file_does_not_exists),
					Toast.LENGTH_SHORT).show();
			return;
		}
		Intent intent = new Intent();
		final String fileName = aFile.getName().toLowerCase();
		Uri data = FileUtil.getUri(aFile);
		if (TAG_FLAG)
			Log.d(TAG, "################## FileUri = " + data);

		if (fileName.toLowerCase().endsWith(".ics")) {
			intent.setAction("com.android.calendar.import");
			intent.putExtra("Operation", "add");
			intent.putExtra("Path", Uri.fromFile(aFile).toString());
			context.sendBroadcast(intent);
			// add by PH 091022
			/*
			 * if (context instanceof FileBrowser) { FileBrowser my =
			 * (FileBrowser) context; my.browseTo(new File("/sdcard")); }
			 */
			// end PH 091022
		} else if (fileName.endsWith(".p12") || fileName.endsWith(".cer")
				|| fileName.endsWith(".crt")) {
			// Credentials.getInstance().installFromSdCardWithPath(this,
			// aFile.getPath());
			Filemanager.getInstance().key(FileBrowser.this, aFile.getPath());

			// try {
			// FileInputStream stream = new FileInputStream(aFile);
			// ByteArrayOutputStream cert = new ByteArrayOutputStream(1000);
			// byte[] b = new byte[1000];
			// int n;
			// while ((n = stream.read(b)) != -1)
			// cert.write(b, 0, n);
			// stream.close();
			// cert.close();
			// Log.d("Certtool",
			// "certificate install.............................................................................");
			// if (CertTool.getInstance().isPkcs12Key(cert.toByteArray())) {
			// CertTool.getInstance().addCertificate(cert.toByteArray(),
			// context);
			// } else {
			// Toast.makeText(
			// context,
			// aFile
			// + getString(R.string.application_not_available),
			// Toast.LENGTH_SHORT).show();
			// Log.d("error file",
			// "zhang...........................................");
			// }
			// } catch (IOException e) {
			// Log.i(TAG,
			// "**************************** catch a IOException in addCertificate");
			// }
		} else if (fileName.toLowerCase().endsWith(".zip")/*
														 * ||
														 * fileName.toLowerCase
														 * ().endsWith(".rar")
														 */) {
			new AlertDialog.Builder(context)
					.setMessage(R.string.decompressorhint)
					.setPositiveButton(R.string.alert_dialog_ok,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									onDecompress(aFile);
								}
							})
					.setNegativeButton(R.string.alert_dialog_cancel,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
								}
							}).show();

		} else {
			String type = mMimeTypes.getMimeType(aFile.getName().toLowerCase());
			if (type != null && type.startsWith("image")) {
				intent.putExtra(MediaStore.EXTRA_SHOW_ACTION_ICONS, true);
			}
			intent.setAction(Intent.ACTION_VIEW);
			intent.setDataAndType(data, type);
			try {
				context.startActivity(intent);
			} catch (ActivityNotFoundException e) {
				new AlertDialog.Builder(context)
						.setMessage(R.string.application_not_available)
						.setPositiveButton(R.string.alert_dialog_ok,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
									}
								}).show();
			}
		}
		updateFlag = false;
		openFlag = true;
	}

	// end PH 091011

	// add by PH 091016
	HashMap<String, Drawable> mMimeIconMap;

	private Drawable getDrawableForMimetype(String mimetype) {
		Drawable icon = null;
		if (mMimeIconMap == null) {
			mMimeIconMap = new HashMap<String, Drawable>();
		}

		icon = mMimeIconMap.get(mimetype);
		if (icon == null) {
			PackageManager pm = getPackageManager();
			Intent intent = new Intent(Intent.ACTION_VIEW);
			// intent.setType(mimetype);
			intent.setDataAndType(Uri.fromParts("file", "", null), mimetype);

			List<ResolveInfo> lri = pm.queryIntentActivities(intent,
					PackageManager.MATCH_DEFAULT_ONLY);
			List<ResolveInfo> lriRe = pm.queryBroadcastReceivers(intent,
					PackageManager.MATCH_DEFAULT_ONLY);
			if (lri != null && lri.size() > 0) {
				icon = lri.get(0).loadIcon(pm);
			} else if (lriRe != null && lriRe.size() > 0) {
				icon = lriRe.get(0).loadIcon(pm);
			}

			if (icon != null) {
				mMimeIconMap.put(mimetype, icon);
			} else if (mimetype.equals(ZIP_MIMETYPE)) { // add 2010-12-13 by xqm
				icon = getResources().getDrawable(R.drawable.zip);
				mMimeIconMap.put(mimetype, icon);
			} else {
				icon = getResources().getDrawable(R.drawable.icon_unknown_file);
				mMimeIconMap.put(mimetype, icon);
			}
		}

		return icon;
	}

	private void addAllElements(List<IconifiedText> addTo,
			List<IconifiedText> addFrom) {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%addAllElements");
		for (int i = 0; i < addFrom.size(); i++) {
			addTo.add(addFrom.get(i));
		}
	}

	public static HzToPy mHz2Py = null;

	Comparator<IconifiedText> mSortWay = new Comparator<IconifiedText>() {
		public int compare(IconifiedText n1, IconifiedText n2) {
			int ret = 1;
			try {
				if (mHz2Py == null) {
					mHz2Py = new HzToPy(FileBrowser.this);
				}

				int i = 0;
				String sChar1 = null, sChar2 = null;
				while (true) {
					// if(browsetoThreadFlag && mBrowseToThread.mStop)
					// break;
					String sPy1 = n1.getCharPy(i);
					String sPy2 = n2.getCharPy(i);

					if (sPy1 == null && sPy2 == null) {
						if (i < n1.getText().length())
							sChar1 = n1.getText().substring(i, i + 1);
						else
							return -1;

						if (i < n2.getText().length())
							sChar2 = n2.getText().substring(i, i + 1);
						else
							return 1;

						if (sChar2.equalsIgnoreCase(sChar1)) {
							String sPy = mHz2Py.Char2Py(sChar1.charAt(0));
							n1.appendPy(sPy);
							n2.appendPy(sPy);
							continue;
						} else {
							n1.appendPy(mHz2Py.Char2Py(sChar1.charAt(0)));
							n2.appendPy(mHz2Py.Char2Py(sChar2.charAt(0)));
							continue;
						}
					} else if (sPy1 == null) {
						if (i < n1.getText().length())
							sChar1 = n1.getText().substring(i, i + 1);
						else
							return -1;

						sChar2 = n2.getText().substring(i, i + 1);
						if (sChar2.equalsIgnoreCase(sChar1)) {
							n1.appendPy(n2.getCharPy(i));
							continue;
						} else {
							n1.appendPy(mHz2Py.Char2Py(sChar1.charAt(0)));
							continue;
						}
					} else if (sPy2 == null) {
						if (i < n2.getText().length())
							sChar2 = n2.getText().substring(i, i + 1);
						else
							return 1;

						sChar1 = n1.getText().substring(i, i + 1);
						if (sChar1.equalsIgnoreCase(sChar2)) {
							n2.appendPy(n1.getCharPy(i));
							continue;
						} else {
							n2.appendPy(mHz2Py.Char2Py(sChar2.charAt(0)));
							continue;
						}
					} else {
						int nRet = sPy1.compareTo(sPy2);
						if (nRet == 0) {
							i += 1;
							continue;
						}

						return nRet;
					}
				}
			} catch (IOException e) {
				if (TAG_FLAG)
					Log.i(TAG,
							"**************catch a IOException in mHz2Py***************");
			}
			return ret;
		}
	};

	private void addIconifiedTextToList(IconifiedText item,
			List<IconifiedText> list) {
		int nIndex1 = 0;
		int nIndex2 = list.size() - 1;
		int nIndex = 0;

		if (nIndex2 < 0) {
			list.add(item);
			return;
		}

		while (true) {
			nIndex = (nIndex2 + nIndex1) / 2;
			IconifiedText temp = list.get(nIndex);

			int result = mSortWay.compare(item, temp);
			if (result > 0) {
				nIndex1 = nIndex + 1;
			} else if (result < 0) {
				nIndex2 = nIndex - 1;
			} else {
				list.add(nIndex, item);
				break;
			}

			if (nIndex1 > nIndex2) {
				if (result > 0) {
					if (nIndex >= list.size() - 1) {
						list.add(item);
					} else {
						list.add(nIndex + 1, item);
					}
				} else {
					list.add(nIndex, item);
				}

				break;
			}
		}
	}

	private void sortedFileList(File[] files) {
		if (TAG_FLAG)
			Log.i(TAG, "==> sortedFileList");

		if (files == null) {
			return;
		}

		// if(mBrowseToThread != null && mBrowseToThread.mStop)
		// return;

		Drawable currentSysIcon = getResources().getDrawable(
				R.drawable.icon_folder_sys);
		Drawable currentUsrIcon = getResources().getDrawable(
				R.drawable.icon_default_folder);
		Drawable fileIcon = null;

		this.mListDir.clear();
		this.mListFile.clear();
		this.mListSys.clear();
		this.directoryEntries.clear();

		for (File currentFile : files) {
			if (browsetoThreadFlag && mBrowseToThread.mStop)
				break;
			if (currentFile.isHidden()) {
				continue;
			}

			/*
			 * add 2010-11-4 xie
			 */
			if (currentFile.isDirectory()) {
				if (!Constant.isSysOrReservedDir(this, currentFile)
						&& !currentFile.getName().toUpperCase()
								.equals(Constant.invalidDir)) {
					// if (currentIcon == null)
					switch (this.displayMode) {
					case ABSOLUTE:
					case RELATIVE:
						if (TAG_FLAG) {
							Log.d(TAG,
									"currentUsrIcon============================="
											+ currentUsrIcon);
							Log.d(TAG,
									"currentFile============================="
											+ currentFile);
							Log.d(TAG, "mListDir============================="
									+ mListDir);
						}
						addIconifiedTextToList(new IconifiedText(
								currentUsrIcon, currentFile, false), mListDir);
						break;
					}
				} else if (Constant.isSysOrReservedDir(this, currentFile)
						&& !currentFile.getName().toUpperCase()
								.equals(Constant.invalidDir)) {
					switch (this.displayMode) {
					case ABSOLUTE:
					case RELATIVE:
						addIconifiedTextToList(new IconifiedText(
								currentSysIcon, currentFile, true), mListSys);
						break;
					}
				}
			}

			else {
				String fileName = currentFile.getName();
				// add by PH 091016
				String mimetype = mMimeTypes
						.getMimeType(fileName.toLowerCase());
				if (mimetype == null) {
					if (FileUtil.getExtension(fileName).equals(".p12")) {
						fileIcon = getResources().getDrawable(
								R.drawable.ic_menu_login);
					} else {
						fileIcon = getResources().getDrawable(
								R.drawable.icon_unknown_file);
					}
				} else {
					fileIcon = getDrawableForMimetype(mimetype);
				}
				// end PH 091016

				switch (this.displayMode) {
				case ABSOLUTE:
				case RELATIVE:
					addIconifiedTextToList(new IconifiedText(fileIcon,
							currentFile, false), mListFile);
					break;
				}
			}
		}

		// Log.d(TAG,
		// "###################### directoryEntries = "+directoryEntries);
		addAllElements(directoryEntries, mListSys);
		addAllElements(directoryEntries, mListDir);
		addAllElements(directoryEntries, mListFile);

		if (!browsetoThreadFlag) {
			Log.i(TAG, "update UI");
			// if (State == Constant._LIST) {
			// add xieqm 110112
			if (itemList == null) {
				itemList = new IconifiedTextListAdapter(this,
						this.directoryEntries);
				this.itemList.setListItems(directoryEntries);
			} else {
				this.itemList.setListItems(directoryEntries);
			}
			// end
			mlvContent.setAdapter(itemList);
			// if (mlvContent.getAdapter() != itemList) {
			// mlvContent.setAdapter(itemList);
			// }
			// else {
			// itemList.notifyDataSetChanged();
			// }

			TextView t = (TextView) findViewById(R.id.empty);
			if (directoryEntries.size() == 0) {
				nothing = true;
				t.setText(R.string.not_found);
				t.setVisibility(View.VISIBLE);
			} else {
				nothing = false;
				t.setVisibility(View.GONE);

				if (null != mpstCur) {
					File dir = mpstCur.getDir();
					if (dir.equals(currentDirectory)) {
						mlvContent.setSelection(mpstCur.getIndex());
					} else {
						mlvContent.setSelection(0);
					}
				} else {
					mlvContent.setSelection(0);
				}

			}

			// } else if (State == Constant._SELECT) {
			/*
			 * this.itemSelect.setListItems(directoryEntries); if
			 * (this.getListAdapter() != itemSelect) {
			 * this.setListAdapter(itemSelect); } else {
			 * itemSelect.notifyDataSetChanged(); } }
			 */

		}
	}

	/**
	 * Checks whether checkItsEnd ends with one of the Strings from fileEndings
	 */
	private static boolean checkEndsWithInStringArray(String checkItsEnd,
			String[] fileEndings) {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%checkEndsWithInStringArray");
		for (String aEnd : fileEndings) {
			if (checkItsEnd.toLowerCase().endsWith(aEnd))
				return true;
		}
		return false;
	}

	public void onCreateContextMenu(ContextMenu menu, View view,
			ContextMenuInfo menuInfo) {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%onCreateContextMenu");
		if (State == _SELECT)
			return;
		else if (State == _LIST) {
			super.onCreateContextMenu(menu, view, menuInfo);
			AdapterView.AdapterContextMenuInfo info;
			try {
				info = (AdapterView.AdapterContextMenuInfo) menuInfo;
			} catch (ClassCastException e) {
				if (TAG_FLAG)
					Log.e(TAG, "***********bad menuInfo************", e);
				return;
			}
			IconifiedText ob = (IconifiedText) mlvContent.getAdapter().getItem(
					info.position);
			if (ob == null || ob.getFile() == null)
				return;
			if (ob.getFile().isFile()) {
				menu.add(0, DEL_ID, 0, R.string.menu_delete);
				menu.add(0, CUT_ID, 0, R.string.menu_cut);
				menu.add(0, COPY_ID, 0, R.string.menu_copy);
				menu.add(0, PRE_UPLOAD, 0, R.string.upload);
				menu.add(0, SEND_ID, 0, R.string.menu_send);
				/*
				 * if (checkEndsWithInStringArray(ob.getText(), getResources()
				 * .getStringArray(R.array.fileEndingPackage))) { menu.add(0,
				 * DECOMPRESS_ID, 0, R.string.menu_decompress); menu.add(0,
				 * COMPRESS_ID, 0, R.string.menu_compress); // add by PH 091021
				 * } else { menu.add(0, COMPRESS_ID, 0, R.string.menu_compress);
				 * }
				 */
				if (FileUtil.getExtension(ob.getText()).equals(".zip")) {
					menu.add(0, DECOMPRESS_ID, 0, R.string.menu_decompress);
					menu.add(0, COMPRESS_ID, 0, R.string.menu_compress); // add
																			// by
																			// PH
																			// 100301
				} else {
					menu.add(0, COMPRESS_ID, 0, R.string.menu_compress);
				}

				// menu.add(0, COMPRESS_ID, 0, R.string.menu_compress);
				menu.add(0, RENAME_ID, 0, R.string.menu_rename);
				menu.add(0, ATTRIDIS_ID, 0, R.string.menu_disattri);
			}
			/*
			 * add 2010-11-4 xie
			 */
			if (ob.getFile().isDirectory()) {
				// Log.d(TAG, "*************isDirectory ********* ");
				if (Constant.isSysOrReservedDir(this, ob.getFile()) == false) {
					menu.add(0, DEL_ID, 0, R.string.menu_delete);
					menu.add(0, CUT_ID, 0, R.string.menu_cut);
				}
				menu.add(0, COPY_ID, 0, R.string.menu_copy);
				menu.add(0, PRE_UPLOAD, 0, R.string.upload);
				menu.add(0, COMPRESS_ID, 0, R.string.menu_compress);
				if (Constant.isSysOrReservedDir(this, ob.getFile()) == false) {
					menu.add(0, RENAME_ID, 0, R.string.menu_rename);
				}
				menu.add(0, ATTRIDIS_ID, 0, R.string.menu_disattri);
			}
			// ///////////
		}
	}

	public boolean onContextItemSelected(MenuItem item) {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%onContextItemSelected");
		cut_copy = false;
		this.itemList.notifyDataSetChanged();
		if (!MarkedFile.isEmpty()) {
			MarkedFile.clear();
			isSelected = false;
		}
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		final IconifiedText ob = (IconifiedText) mlvContent.getAdapter()
				.getItem(info.position);
		String filePath = ob.getFile().getAbsolutePath();
//		for(int i=0;i<20;i++){
//			Log.d("FileBrowser","######################## real filepath is: " + filePath);
//		}
		if (ob == null || ob.getFile() == null)
			return false;
		MarkedFile.add(ob.getFile());
		switch (item.getItemId()) {
		case DEL_ID:
			delFile();
			break;
		case COPY_ID:
			opType = OPTYPE.COPY;
			cut_copy = true;
			FileClipBoard fcbMarked = FileClipBoard.getInstance();
			fcbMarked.clear();
			fcbMarked.setOperation(FileClipBoard.OP_COPY);
			for (int i = 0; i < MarkedFile.size(); i++) {
				File file = MarkedFile.get(i);
				if (!fcbMarked.hasIt(file)) {
					fcbMarked.addFile(file);
				}
			}
			break;
		case PRE_UPLOAD:
			uploadFile = new String[1];
			uploadFileTypes = new boolean[1];
			uploadFile[0] = ob.getFile().getAbsolutePath();
			uploadFileTypes[0] = ob.getFile().isDirectory();
			preUpload();
			break;
		case CUT_ID:
			// set the both cut-or-copy flags
			opType = OPTYPE.CUT;
			cut_copy = true;
			// darken the selected items
			darkSelectedItem();
			this.itemList.notifyDataSetChanged();
			// refreshScr();
			break;
		case COMPRESS_ID:
			onCompress();
			// compressDialog();
			break;
		case DECOMPRESS_ID:
			onDecompress(ob.getFile());
			break;
		case RENAME_ID:
			boolean isdownLoadOver = isFileDownLoadOver(filePath);
			boolean isupLoadOver = isFileUpLoadOver(filePath);
//			if (!isdownLoadOver) {// NetDiskManager.isDownLoadWork(ob.getFile().getAbsolutePath())
//				Log.d(TAG, "==> isDownLoadWork");
//				ErrorMessageDialog.showMessageDialog(FileBrowser.this,
//						getString(R.string.download_no_finish));
//			} else if (!isupLoadOver) {// NetDiskManager.isUpLoadWork(ob.getFile().getAbsolutePath())
//				Log.d(TAG, "==> isUpLoadWork");
//				ErrorMessageDialog.showMessageDialog(FileBrowser.this,
//						getString(R.string.upload_no_finish));
//			} else {
//				onRename(ob.getFile());
//			}
			
			if (!isdownLoadOver || !isupLoadOver) {// NetDiskManager.isDownLoadWork(filePath[i]))
				Log.d(TAG, "==> isDownLoadWork");
				ErrorMessageDialog.showMessageDialog(FileBrowser.this,
						getString(R.string.upload_or_download_now));
				break;
			} else {
				onRename(ob.getFile());
			}
			break;
		case ATTRIDIS_ID:
			disAttri();
			break;
		case SEND_ID:
			sendFile(ob.getFile());
			break;
		default:
			return super.onContextItemSelected(item);
		}
		return true;

	}

	private void preUpload() {
		new AlertDialog.Builder(FileBrowser.this)
				.setTitle(R.string.upload)
				.setMessage(R.string.upload_detail)
				.setPositiveButton(R.string.alert_dialog_ok,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								if (TAG_FLAG) {
									Log.e(TAG, "==> preUpload");
								}
								isUpload = true;
								loginLenovo();
							}
						})
				.setNeutralButton(R.string.alert_dialog_cancel,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
							}
						}).show();
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		// return super.onCreateOptionsMenu(menu);
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%onCreateOptionsMenu");
		boolean result = super.onCreateOptionsMenu(menu);
		inputMethodManager.hideSoftInputFromWindow(mlvContent.getWindowToken(),
				0);
		isSelected = false;
		// menu item for LIST state, group id is 0
		menu.add(0, SELECT_ID, 0, R.string.menu_edit).setIcon(
				R.drawable.ic_menu_edit);
		menu.add(0, PASTE_ID, 0, R.string.menu_paste).setIcon(
				R.drawable.ic_menu_paste);
		// add by xieqm 110225
		menu.add(0, SWITCHING_DIRECTORY, 0, R.string.switching_directory)
				.setIcon(R.drawable.switch_directory);
		// end
		menu.add(0, NEW_ID, 0, R.string.menu_new).setIcon(
				R.drawable.ic_menu_add);
		// menu item for SELECT state, group id is 1
		menu.add(1, DEL_ID, 0, R.string.menu_delete).setIcon(
				R.drawable.ic_menu_delete);
		menu.add(1, CUT_ID, 0, R.string.menu_cut).setIcon(
				R.drawable.ic_menu_cut);
		menu.add(1, COPY_ID, 0, R.string.menu_copy).setIcon(
				R.drawable.ic_menu_copy);
		menu.add(1, COMPRESS_ID, 0, R.string.menu_compress).setIcon(
				R.drawable.ic_menu_compress);
		// add 2010-12-13 by xqm
		if (menuFlag == true) {
			result = true;
		} else {
			result = false;
		}
		// end
		return result;
	}

	public boolean onPrepareOptionsMenu(Menu menu) {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%onPrepareOptionsMenu");
		// super.onPrepareOptionsMenu(menu);
		if (TAG_FLAG) {
			Log.d(TAG, "the sdRemoved is =============" + sdRemoved);
			Log.d(TAG, "the isSelected is =============" + isSelected);
			Log.d(TAG, "the nothing is ================" + nothing);
		}
		inputMethodManager.hideSoftInputFromWindow(mlvContent.getWindowToken(),
				0);
		switch (State) {
		case _LIST:
			if (!sdRemoved) {
				// visible items of LIST state
				menu.setGroupVisible(0, true);
				// invisible items of SELECT state
				menu.setGroupVisible(1, false);
				// make "paste" invisible, only if Cut or Copy action is coming
				if (!cut_copy) {
					menu.findItem(PASTE_ID).setVisible(false);
				} else
					menu.findItem(PASTE_ID).setVisible(true);

				if (nothing) {
					menu.findItem(SELECT_ID).setVisible(false);
				} else {
					menu.findItem(SELECT_ID).setVisible(true);
				}
			} else {
				menu.setGroupVisible(0, false);
				// invisible items of SELECT state
				menu.setGroupVisible(1, false);
			}
			break;
		case _SELECT:
			// visible items of SELECT state
			menu.setGroupVisible(1, true);
			// invisible items of LIST state
			menu.setGroupVisible(0, false);
			// if no file is selected unable items
			// add by PH 091113
			if (!isSelected || nothing) {
				menu.setGroupEnabled(1, false);
			} else {
				menu.setGroupEnabled(1, true);
			}
			// end PH 091113
			break;
		}
		return true;

	}

	public boolean onOptionsItemSelected(MenuItem item) {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%onOptionsItemSelected");
		switch (item.getItemId()) {
		case SELECT_ID:
			// list2select();
			if (cut_copy) {
				if (!MarkedFile.isEmpty()) {
					MarkedFile.clear();
					isSelected = false;
				}
				cut_copy = false;
			}
			State = _SELECT;
			initState();
			setLocationText(currentDirectory.getPath());
			updateFlag = true; // add 2010-11-27 by xie
			break;
		case PASTE_ID:
			onPaste();
			break;
		case SWITCHING_DIRECTORY:
			switchingDirectory();
			break;
		case NEW_ID:
			// if "copy" or "cut" item was clicked, but there was no "paste"
			// followed, recover the slection state
			if (cut_copy) {
				// unmarkallFile();
				if (!MarkedFile.isEmpty()) {
					MarkedFile.clear();
					isSelected = false;
				}
				cut_copy = false;
				this.itemList.notifyDataSetChanged();
			}
			new AlertDialog.Builder(FileBrowser.this)
					.setTitle(R.string.create_file)
					.setItems(R.array.create_dialog_items,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									/* User clicked so do some stuff */
									switch (which) {
									case 0:
										LayoutInflater factory = LayoutInflater
												.from(FileBrowser.this);
										final View textEntryView = factory
												.inflate(
														R.layout.alert_dialog_text_entry,
														null);
										final TextView textView = (TextView) textEntryView
												.findViewById(R.id.filename_view);
										textView.setText(R.string.new_directoryname);
										final EditText eText = (EditText) textEntryView
												.findViewById(R.id.filename_edit);
										// eText.setText(getDefaultName(currentDirectory.getPath(),getResources().getString(R.string.default_dir_name)));
										eText.setText(getResources().getString(
												R.string.default_dir_name));// add
																			// by
																			// PH//
																			// 091017
										eText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
												FILE_NAME_NUM_MAX) });
										eText.selectAll();// add by PH 091118
										new AlertDialog.Builder(
												FileBrowser.this)
												.setTitle(R.string.inputname)
												.setView(textEntryView)
												.setPositiveButton(
														R.string.alert_dialog_ok,
														new DialogInterface.OnClickListener() {
															public void onClick(
																	DialogInterface dialog,
																	int whichButton) {
																String name = eText
																		.getText()
																		.toString()
																		.trim();
																if (TAG_FLAG)
																	Log.i(TAG,
																			"********name = "
																					+ name
																					+ "**********");
																if (name.length() > 0
																		&& name.length() <= FILE_NAME_NUM_MAX) {
																	if (isNameUseable(
																			name,
																			true) == false) {
																		Toast.makeText(
																				FileBrowser.this,
																				R.string.namebad,
																				Toast.LENGTH_SHORT)
																				.show();
																	} else {
																		File f = new File(
																				currentDirectory
																						.getPath()
																						+ "/"
																						+ name);
																		if (f.exists() == true
																				&& f.isDirectory() == true) {
																			Toast.makeText(
																					FileBrowser.this,
																					R.string.nameexist,
																					Toast.LENGTH_SHORT)
																					.show();
																		} else {
																			creatDir(name);
																		}
																	}
																} else if (name
																		.length() > FILE_NAME_NUM_MAX) {
																	Toast.makeText(
																			FileBrowser.this,
																			R.string.name_too_long,
																			Toast.LENGTH_SHORT)
																			.show();
																} else {
																	Toast.makeText(
																			FileBrowser.this,
																			R.string.nameempty,
																			Toast.LENGTH_SHORT)
																			.show();
																}
															}
														})
												.setNegativeButton(
														R.string.alert_dialog_cancel,
														new DialogInterface.OnClickListener() {
															public void onClick(
																	DialogInterface dialog,
																	int whichButton) {
																// User clicked
																// cancel
																// so do some
																// stuff
															}
														}).show();
										break;
									case 1:
										// TODO call a interface to open WORD
										// document
										LayoutInflater factory_doc = LayoutInflater
												.from(FileBrowser.this);
										final View textEntryView_doc = factory_doc
												.inflate(
														R.layout.alert_dialog_text_entry,
														null);
										final TextView textView_doc = (TextView) textEntryView_doc
												.findViewById(R.id.filename_view);
										textView_doc
												.setText(R.string.new_officename);
										final EditText eText_doc = (EditText) textEntryView_doc
												.findViewById(R.id.filename_edit);
										// Log.i(TAG,"************************1*****************************");
										// eText_doc.setText(getDefaultName(currentDirectory.getPath(),getResources().getString(R.string.default_doc_name)));
										eText_doc
												.setText(getResources()
														.getString(
																R.string.default_doc_name));
										eText_doc
												.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
														OFFICE_FILE_NAME_NUM_MAX) });
										eText_doc.selectAll();// add by PH
																// 091118
										// Log.i(TAG,"************************2*****************************");
										new AlertDialog.Builder(
												FileBrowser.this)
												.setTitle(
														R.string.default_doc_name)
												.setView(textEntryView_doc)
												.setPositiveButton(
														R.string.alert_dialog_ok,
														new DialogInterface.OnClickListener() {
															public void onClick(
																	DialogInterface dialog,
																	int whichButton) {
																StringBuilder name_doc;
																String name = eText_doc
																		.getText()
																		.toString();
																name_doc = new StringBuilder();
																name = name_doc
																		.append(name)
																		.append(".doc")
																		.toString();
																if (FileUtil
																		.getFileNameWithoutExt(
																				name)
																		.length() > 0
																		&& name.length() <= FILE_NAME_NUM_MAX) {

																	if (isNameUseable(
																			name,
																			true) == false) {
																		Toast.makeText(
																				FileBrowser.this,
																				R.string.namebad,
																				Toast.LENGTH_SHORT)
																				.show();
																	} else {
																		File f = new File(
																				currentDirectory
																						.getPath()
																						+ "/"
																						+ name);
																		if (f.exists() == true
																				&& f.isFile() == true) {
																			Toast.makeText(
																					FileBrowser.this,
																					R.string.nameexist,
																					Toast.LENGTH_SHORT)
																					.show();
																		} else {
																			// creatDir(name);
																			officeFlag = 1;
																			createOffice(name);
																			// Toast.makeText(FileBrowser.this,
																			// R.string.docOk,
																			// Toast.LENGTH_SHORT).show();
																		}
																	}

																} else if (name
																		.length() > FILE_NAME_NUM_MAX) {
																	Toast.makeText(
																			FileBrowser.this,
																			R.string.name_too_long,
																			Toast.LENGTH_SHORT)
																			.show();
																} else {
																	Toast.makeText(
																			FileBrowser.this,
																			R.string.nameempty,
																			Toast.LENGTH_SHORT)
																			.show();
																}
															}
														})
												.setNegativeButton(
														R.string.alert_dialog_cancel,
														new DialogInterface.OnClickListener() {
															public void onClick(
																	DialogInterface dialog,
																	int whichButton) {
																// User clicked
																// cancel
																// so do some
																// stuff
															}
														}).show();
										break;
									case 2:
										// TODO call a interface to open EXCEL
										// document
										LayoutInflater factory_xls = LayoutInflater
												.from(FileBrowser.this);
										final View textEntryView_xls = factory_xls
												.inflate(
														R.layout.alert_dialog_text_entry,
														null);
										final TextView textView_xls = (TextView) textEntryView_xls
												.findViewById(R.id.filename_view);
										textView_xls
												.setText(R.string.new_officename);
										final EditText eText_xls = (EditText) textEntryView_xls
												.findViewById(R.id.filename_edit);
										// eText_xls.setText(getDefaultName(currentDirectory.getPath(),getResources().getString(R.string.default_xls_name)));
										eText_xls
												.setText(getResources()
														.getString(
																R.string.default_xls_name));
										eText_xls
												.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
														OFFICE_FILE_NAME_NUM_MAX) });
										eText_xls.selectAll();// add by PH
																// 091118
										new AlertDialog.Builder(
												FileBrowser.this)
												.setTitle(
														R.string.default_xls_name)
												.setView(textEntryView_xls)
												.setPositiveButton(
														R.string.alert_dialog_ok,
														new DialogInterface.OnClickListener() {
															public void onClick(
																	DialogInterface dialog,
																	int whichButton) {
																StringBuilder name_xls;
																String name = eText_xls
																		.getText()
																		.toString();
																name_xls = new StringBuilder();
																name = name_xls
																		.append(name)
																		.append(".xls")
																		.toString();
																if (FileUtil
																		.getFileNameWithoutExt(
																				name)
																		.length() > 0
																		&& name.length() <= FILE_NAME_NUM_MAX) {

																	if (isNameUseable(
																			name,
																			true) == false) {
																		Toast.makeText(
																				FileBrowser.this,
																				R.string.namebad,
																				Toast.LENGTH_SHORT)
																				.show();
																	} else {
																		File f = new File(
																				currentDirectory
																						.getPath()
																						+ "/"
																						+ name);
																		if (f.exists() == true
																				&& f.isFile() == true) {
																			Toast.makeText(
																					FileBrowser.this,
																					R.string.nameexist,
																					Toast.LENGTH_SHORT)
																					.show();
																		} else {
																			// creatDir(name);
																			officeFlag = 2;
																			createOffice(name);
																			// Toast.makeText(FileBrowser.this,
																			// R.string.xlsOk,
																			// Toast.LENGTH_SHORT).show();
																		}
																	}

																} else if (name
																		.length() > FILE_NAME_NUM_MAX) {
																	Toast.makeText(
																			FileBrowser.this,
																			R.string.name_too_long,
																			Toast.LENGTH_SHORT)
																			.show();
																} else {
																	Toast.makeText(
																			FileBrowser.this,
																			R.string.nameempty,
																			Toast.LENGTH_SHORT)
																			.show();
																}
															}
														})
												.setNegativeButton(
														R.string.alert_dialog_cancel,
														new DialogInterface.OnClickListener() {
															public void onClick(
																	DialogInterface dialog,
																	int whichButton) {
																// User clicked
																// cancel/// so
																// do some stuff
															}
														}).show();
										break;
									case 3:
										// TODO call a interface to open PPT
										// document
										LayoutInflater factory_ppt = LayoutInflater
												.from(FileBrowser.this);
										final View textEntryView_ppt = factory_ppt
												.inflate(
														R.layout.alert_dialog_text_entry,
														null);
										final TextView textView_ppt = (TextView) textEntryView_ppt
												.findViewById(R.id.filename_view);
										textView_ppt
												.setText(R.string.new_officename);
										final EditText eText_ppt = (EditText) textEntryView_ppt
												.findViewById(R.id.filename_edit);
										// eText_ppt.setText(getDefaultName(currentDirectory.getPath(),getResources().getString(R.string.default_ppt_name)));
										eText_ppt
												.setText(getResources()
														.getString(
																R.string.default_ppt_name));
										eText_ppt
												.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
														OFFICE_FILE_NAME_NUM_MAX) });
										eText_ppt.selectAll();// add by PH
																// 091118
										new AlertDialog.Builder(
												FileBrowser.this)
												.setTitle(
														R.string.default_ppt_name)
												.setView(textEntryView_ppt)
												.setPositiveButton(
														R.string.alert_dialog_ok,
														new DialogInterface.OnClickListener() {
															public void onClick(
																	DialogInterface dialog,
																	int whichButton) {
																StringBuilder name_ppt;
																String name = eText_ppt
																		.getText()
																		.toString();
																name_ppt = new StringBuilder();
																name = name_ppt
																		.append(name)
																		.append(".ppt")
																		.toString();
																if (FileUtil
																		.getFileNameWithoutExt(
																				name)
																		.length() > 0
																		&& name.length() <= FILE_NAME_NUM_MAX) {

																	if (isNameUseable(
																			name,
																			true) == false) {
																		Toast.makeText(
																				FileBrowser.this,
																				R.string.namebad,
																				Toast.LENGTH_SHORT)
																				.show();
																	} else {
																		File f = new File(
																				currentDirectory
																						.getPath()
																						+ "/"
																						+ name);
																		if (f.exists() == true
																				&& f.isFile() == true) {
																			Toast.makeText(
																					FileBrowser.this,
																					R.string.nameexist,
																					Toast.LENGTH_SHORT)
																					.show();
																		} else {
																			// creatDir(name);
																			officeFlag = 3;
																			createOffice(name);
																			// Toast.makeText(FileBrowser.this,
																			// R.string.pptOk,
																			// Toast.LENGTH_SHORT).show();
																		}
																	}

																} else if (name
																		.length() > FILE_NAME_NUM_MAX) {
																	Toast.makeText(
																			FileBrowser.this,
																			R.string.name_too_long,
																			Toast.LENGTH_SHORT)
																			.show();
																} else {
																	Toast.makeText(
																			FileBrowser.this,
																			R.string.nameempty,
																			Toast.LENGTH_SHORT)
																			.show();
																}
															}
														})
												.setNegativeButton(
														R.string.alert_dialog_cancel,
														new DialogInterface.OnClickListener() {
															public void onClick(
																	DialogInterface dialog,
																	int whichButton) {
																// User clicked
																// cancel
																// so do some
																// stuff
															}
														}).show();
										break;
									}
								}
							}).show();
			updateFlag = true; // add 2010-11-27 by xie
			break;
		case COPY_ID:
			// set the both cut-or-copy flags
			FileClipBoard fcbMarked = FileClipBoard.getInstance();
			fcbMarked.clear();
			fcbMarked.setOperation(FileClipBoard.OP_COPY);
			for (int i = 0; i < MarkedFile.size(); i++) {
				File file = MarkedFile.get(i);
				if (!fcbMarked.hasIt(file)) {
					fcbMarked.addFile(file);
				}
			}

			opType = OPTYPE.COPY;
			cut_copy = true;
			State = _LIST;
			initState();
			updateFlag = true; // add 2010-11-27 by xie
			break;
		case CUT_ID:
			// set the both cut-or-copy flags
			if (MarkedFile.isEmpty()) {
				Toast.makeText(this, R.string.nosource, 3).show();
				break;
			}
			opType = OPTYPE.CUT;
			cut_copy = true;
			// protect the system directories not to be cut.
			protectSysDir();
			if (MarkedFile.isEmpty()) {
				cut_copy = false;
				if (State == _SELECT) {
					State = _LIST;
					initState();
				}
				break;
			}
			// darken the selected items
			darkSelectedItem();
			// change state to LIST
			if (State == _SELECT) {
				State = _LIST;
				initState();
			}
			updateFlag = true; // add 2010-11-27 by xie
			break;
		case DEL_ID:
			if (MarkedFile.isEmpty()) {
				Toast.makeText(this, R.string.nosource, 3).show();
				break;
			}
			boolean sysFlag = false;// add 2010-12-10 by xqm
			int flag = 0;
			int gpsmap_flag = 0;
			// select2list();
			State = Constant._LIST;
			initState();
			// add by PH 091102
			if (TAG_FLAG)
				Log.i(TAG, "MarkedFileMarkedFile========" + MarkedFile.get(0));
			List<File> sysDirs = Constant.getSysDir(this, MarkedFile);
			// Log.i(TAG, "********MarkedFile="+MarkedFile+"*******");
			// Log.i(TAG, "********sysdirs="+sysDirs+"*******");
			for (File sysDir : sysDirs) {
				if (MarkedFile.contains(sysDir)) {
					flag = 1;// sys
					sysFlag = true;// add 2010-12-10 by xqm
					break;
				} else {
					flag = 0;// notsys
				}
			}
			if (sysDirs.containsAll(MarkedFile)) {
				flag = 2; // all sys
			}
			File gpsmap = new File("/sdcard/gpsmap");
			if (MarkedFile.contains(gpsmap)) {
				gpsmap_flag = 1; // gpsmap
			} else {
				gpsmap_flag = 0; // notgpsmap
			}
			// end PH 091102
			if (flag == 1) {
				// add 2010-12-10 by xqm
				if (sysFlag) {
					new AlertDialog.Builder(FileBrowser.this)
							.setTitle(R.string.remind)
							.setMessage(R.string.alert_dialog_two_buttons_title)
							.setPositiveButton(R.string.alert_dialog_ok,
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int whichButton) {
											/* User clicked OK so do some stuff */
											// delFile();
											protectSysDir();
											if (MarkedFile.isEmpty()) {
												Toast.makeText(
														FileBrowser.this,
														R.string.error_file_does_not_exists,
														3);
												return;
											}

											FileClipBoard fcbMarked = FileClipBoard
													.getInstance();
											fcbMarked.clear();
											fcbMarked
													.setOperation(FileClipBoard.OP_DELETE);
											for (int i = 0; i < MarkedFile
													.size(); i++) {
												File file = MarkedFile.get(i);
												if (!fcbMarked.hasIt(file)) {
													fcbMarked.addFile(file);
												}
											}
											Log.i(TAG, "the marked files is "
													+ MarkedFile.size());
											Bundle bundle = new Bundle();
											bundle.putInt(
													FileOp.KEY_INT_FOP_CODE,
													FileOp.FOP_DELETE);
											bundle.putInt(
													FileOp.KEY_INT_SRC_FROM,
													FileOp.SRC_FROM_CLIP);
											callFileManDoAction(bundle,
													FileOp.FOP_DELETE);
											if (TAG_FLAG)
												Log.i(TAG,
														"delFile-----------------------------------------delFile");
										}
									})
							.setNegativeButton(R.string.alert_dialog_cancel,
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int whichButton) {
											/*
											 * User clicked Cancel so do some
											 * stuff
											 */
										}
									}).show();
				} else {
					if (MarkedFile.size() > 1) {
						if (gpsmap_flag == 1) {
							new AlertDialog.Builder(FileBrowser.this)
									.setTitle(R.string.remind)
									.setMessage(
											R.string.alert_dialog_del_sys_gpsmap)
									.setPositiveButton(
											R.string.alert_dialog_ok,
											new DialogInterface.OnClickListener() {
												public void onClick(
														DialogInterface dialog,
														int whichButton) {
													/*
													 * User clicked OK so do
													 * some stuff
													 */
													delFile();
												}
											})
									.setNegativeButton(
											R.string.alert_dialog_cancel,
											new DialogInterface.OnClickListener() {
												public void onClick(
														DialogInterface dialog,
														int whichButton) {
													/*
													 * User clicked Cancel so do
													 * some stuff
													 */
												}
											}).show();
						} else {
							// new AlertDialog.Builder(FileBrowser.this)
							// .setTitle(R.string.remind)
							// .setMessage(R.string.alert_dialog_two_buttons_title)
							// .setPositiveButton(R.string.alert_dialog_ok,new
							// DialogInterface.OnClickListener() {
							// public void onClick(DialogInterface dialog,int
							// whichButton) {
							/* User clicked OK so do some stuff */
							delFile();
							// }
							// })
							// .setNegativeButton(R.string.alert_dialog_cancel,new
							// DialogInterface.OnClickListener() {
							// public void onClick(DialogInterface dialog,int
							// whichButton) {
							// /* User clicked Cancel so do some stuff */
							// }
							// }).show();
						}
					} else {
						new AlertDialog.Builder(FileBrowser.this)
								.setTitle(R.string.remind)
								.setMessage(R.string.delete_alert)
								.setNegativeButton(R.string.alert_dialog_ok,
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int whichButton) {
												/*
												 * User clicked Cancel so do
												 * some stuff
												 */
											}
										}).show();
					}
				}
				// end
			} else if (flag == 0) {
				if (MarkedFile.size() > 1) {
					if (gpsmap_flag == 1) {
						new AlertDialog.Builder(FileBrowser.this)
								.setTitle(R.string.remind)
								.setMessage(
										R.string.alert_dialog_delete_some_gpsmap)
								.setPositiveButton(R.string.alert_dialog_ok,
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int whichButton) {
												/*
												 * User clicked OK so do some
												 * stuff
												 */
												delFile();
											}
										})
								.setNegativeButton(
										R.string.alert_dialog_cancel,
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int whichButton) {
												/*
												 * User clicked Cancel so do
												 * some stuff
												 */
											}
										}).show();
					} else {
						// new AlertDialog.Builder(FileBrowser.this)
						// .setTitle(R.string.remind)
						// .setMessage(R.string.alert_dialog_delete_some)
						// .setPositiveButton(R.string.alert_dialog_ok,new
						// DialogInterface.OnClickListener() {
						// public void onClick(DialogInterface dialog,int
						// whichButton) {
						/* User clicked OK so do some stuff */
						delFile();
						// }
						// }).setNegativeButton(R.string.alert_dialog_cancel,new
						// DialogInterface.OnClickListener() {
						// public void onClick(DialogInterface dialog,int
						// whichButton) {
						// /* User clicked Cancel so do some stuff */
						// }
						// }).show();
					}
				} else if (MarkedFile.size() == 1
						&& MarkedFile.get(0).isDirectory()) {
					if (gpsmap_flag == 1) {
						new AlertDialog.Builder(FileBrowser.this)
								.setTitle(R.string.remind)
								.setMessage(R.string.alert_dialog_delete_gpsmap)
								.setPositiveButton(R.string.alert_dialog_ok,
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int whichButton) {
												/*
												 * User clicked OK so do some
												 * stuff
												 */
												delFile();
											}
										})
								.setNegativeButton(
										R.string.alert_dialog_cancel,
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int whichButton) {
												/*
												 * User clicked Cancel so do
												 * some stuff
												 */
											}
										}).show();
					} else {
						delFile();
					}
				} else if (MarkedFile.size() == 1 && MarkedFile.get(0).isFile()) {
					// new AlertDialog.Builder(FileBrowser.this)
					// .setTitle(R.string.remind)
					// .setMessage(R.string.alert_dialog_delete_file)
					// .setPositiveButton(R.string.alert_dialog_ok,new
					// DialogInterface.OnClickListener() {
					// public void onClick(DialogInterface dialog,int
					// whichButton) {
					/* User clicked OK so do some stuff */
					delFile();
					// }
					// }).setNegativeButton(R.string.alert_dialog_cancel,new
					// DialogInterface.OnClickListener() {
					// public void onClick(DialogInterface dialog,int
					// whichButton) {
					// /* User clicked Cancel so do some stuff */
					// }
					// }).show();
				}

			} else {
				if (sysFlag)
					new AlertDialog.Builder(FileBrowser.this)
							.setTitle(R.string.remind)
							.setMessage(R.string.delete_alert)
							.setNegativeButton(R.string.alert_dialog_ok,
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int whichButton) {
											/*
											 * User clicked Cancel so do some
											 * stuff
											 */
										}
									}).show();
			}
			if (TAG_FLAG)
				Log.d(TAG, "flag====================" + flag);
			updateFlag = true; // add 2010-11-27 by xie
			break;
		case COMPRESS_ID:
			// select2list();
			if (MarkedFile.isEmpty()) {
				Toast.makeText(this, R.string.nosource, 3).show();
				break;
			}
			State = _LIST;
			initState();
			onCompress();
			updateFlag = true; // add 2010-11-27 by xie
			break;
		default:
			if (TAG_FLAG)
				Log.i(TAG, "*************unknowed ID**************");
			break;
		}

		return super.onOptionsItemSelected(item);
	}
	private boolean isFileDownLoadOver(String filepath){
		boolean isLoadOver  = downloadServer.isDownLoadOver(filepath);
		return isLoadOver;
	}
	private boolean isFileUpLoadOver(String filepath){
		boolean isLoadOver  = uploadServer.isUpLoadOver(filepath);
		return isLoadOver;
	}
	private void darkSelectedItem() {
		if (MarkedFile.isEmpty()) {
			Toast.makeText(this, R.string.error_file_does_not_exists, 3);
			return;
		}
		String[] filePath = new String[MarkedFile.size()];
		for (int i = 0; i < MarkedFile.size(); i++) {
			filePath[i] = MarkedFile.get(i).getAbsolutePath();
			for(int j=0;j<20;j++){
				Log.d("FileBrowser","####################### filepath is: " + filePath[i]);
			}
			boolean isdownLoadOver = isFileDownLoadOver(filePath[i]);
			boolean isupLoadOver = isFileUpLoadOver(filePath[i]);
//			if (!isdownLoadOver) {// NetDiskManager.isDownLoadWork(filePath[i]))
//				Log.d(TAG, "==> isDownLoadWork");
//				ErrorMessageDialog.showMessageDialog(FileBrowser.this,
//						getString(R.string.download_no_finish));
//				break;
//			} else if (!isupLoadOver) {// NetDiskManager.isUpLoadWork(filePath[i]))
//				Log.d(TAG, "==> isUpLoadWork");
//				ErrorMessageDialog.showMessageDialog(FileBrowser.this,
//						getString(R.string.upload_no_finish));
//				break;
//			} else {
//				Log.d(TAG, "==> not upload or download");
//				curItem();
//				break;
//			}
			//modify by gaoge 2011-04-22
			if (!isdownLoadOver || !isupLoadOver) {// NetDiskManager.isDownLoadWork(filePath[i]))
				Log.d(TAG, "==> isDownLoadWork");
				ErrorMessageDialog.showMessageDialog(FileBrowser.this,
						getString(R.string.upload_or_download_now));
				break;
			} else {
				Log.d(TAG, "==> not upload or download");
				curItem();
				break;
			}
		}

	}

	private void curItem() {
		if (MarkedFile.isEmpty()) {
			Toast.makeText(this, R.string.error_file_does_not_exists, 3);
			return;
		}

		FileClipBoard.getInstance().clear();
		FileClipBoard.getInstance().setOperation(FileClipBoard.OP_CUT);
		for (int i = 0; i < MarkedFile.size(); i++) {
			FileClipBoard.getInstance().addFile(MarkedFile.get(i));
		}
		for (int i = 0; i < directoryEntries.size(); i++) {
			if (MarkedFile.contains(directoryEntries.get(i).getFile())) {
				directoryEntries.get(i).setIsCut(true);
			} else {
				directoryEntries.get(i).setIsCut(false);
			}
		}
	}

	private void renameFile(String path, String oldName, String newName) {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%renameFile");
		// Intent intent = new Intent();
		// intent.setClass(FileBrowser.this, FileMan.class);
		// Bundle bundle = new Bundle();
		// bundle.putInt("request_code", Constant._RENAME);
		// bundle.putString("parent path", path);// modified by PH 091020
		// bundle.putString("oldName", oldName);
		// bundle.putString("newName", newName);
		// intent.putExtras(bundle);
		// startActivityForResult(intent, Constant._RENAME);

		/*
		 * update 2010-11-01 xie
		 */
		if (TAG_FLAG)
			Log.d(TAG, "rename********************rename");
		Bundle bundle = new Bundle();
		bundle.putInt(FileOp.KEY_INT_FOP_CODE, FileOp.FOP_RENAME);
		bundle.putString(FileOp.KEY_STRING_SRC_DIR_PATH, path);
		bundle.putString(FileOp.KEY_STRING_SRC_FILE_NAME, oldName);
		bundle.putString(FileOp.KEY_STRING_DEST_DIR_PATH, newName);
		FileOp.launchActivityToDo(this, bundle, FileOp.FOP_RENAME);
		if (TAG_FLAG)
			Log.d(TAG, "rename----------------------rename");
	}

	/*
	 * decompress the selected zip file to current directory.
	 */
	private void onDecompress(File file) {
		if (TAG_FLAG)
			Log.i(TAG, "%==> decompressFile");

		if (null == file || !file.exists()) {
			if (TAG_FLAG)
				Log.e(TAG, "file is invalid in onDecompress");
		} else {
			checkThenDecompress(file);
		}
	}

	private void checkThenDecompress(File file) {

		if (FileUtil.isCompressFile(file)) {
			decompressFile(file);
		} else {
			if (TAG_FLAG)
				Log.e(TAG,
						"can not decompress this type file in checkThenDecompress");
			Toast.makeText(this, R.string.invalid_compressfile,
					Toast.LENGTH_SHORT).show();
		}
	}

	private void decompressFile(File file) {
		if (TAG_FLAG)
			Log.i(TAG, "==> decompressFile");

		Intent intent = new Intent();
		Bundle bundle = new Bundle();
		String fileName = file.getName();
		String zipfile;

		// bundle.putString("toDir", currentDirectory.getPath()); //2010-11-1
		// zhushi
		// bundle.putString("filename", fileName);

		/*
		 * update 2010-11-1 xie
		 */
		bundle.putString(FileOp.KEY_STRING_DEST_DIR_PATH,
				currentDirectory.getPath());

		if (fileName.toLowerCase().endsWith(".zip")) {
			bundle.putBoolean(FileOp.KEY_BOOLEAN_IS_ZIP, true);
			zipfile = currentDirectory.getPath() + "/" + fileName;
			// bundle.putString("zipfile", zipfile); //2010-11-1 zhushi
			/*
			 * update 2010-11-1 xie
			 */
			// bundle.putString(FileOp.KEY_STRING_SRC_FILE_NAME, fileName);
			bundle.putString(FileOp.KEY_STRING_SRC_FILE_PATH, zipfile);

		} else {
			// bundle.putBoolean("ZIP", false); //2010-11-1 zhushi
			/*
			 * update 2010-11-1 xie
			 */
			bundle.putBoolean(FileOp.KEY_BOOLEAN_IS_ZIP, false);
		}

		// [improve] remove the int request_code
		// bundle.putInt(FileOp.KEY_INT_FOP_CODE, Constant._DECOMPRESS);
		// intent.setClass(this, FileCompressor.class);
		// intent.putExtras(bundle);
		// startActivityForResult(intent, Constant._DECOMPRESS);

		/*
		 * update 2010-11-1 xie
		 */
		bundle.putInt(FileOp.KEY_INT_FOP_CODE, FileOp.FOP_DECOMPRESS);
		FileOp.launchActivityToDo(this, bundle, FileOp.FOP_DECOMPRESS);
		updateFlag = false; // add 2010-12-03 by xie
		openFlag = true; // add 2010-12-03 by xie
	}

	private void onCompress() {
		FileClipBoard.getInstance().clear();
		Log.i(TAG, "the number in MarkedFile is " + MarkedFile.size());
		for (int i = 0; i < MarkedFile.size(); i++) {
			FileClipBoard.getInstance().addFile(MarkedFile.get(i));
		}

		checkThenCompress();
		updateFlag = true; // add 2010-12-03 by xie
		openFlag = true; // add 2010-12-03 by xie
	}

	private void checkThenCompress() {
		if (TAG_FLAG)
			Log.d(TAG, "==> checkThenCompress");

		FileClipBoard fcbMarked = FileClipBoard.getInstance();
		if (fcbMarked.isEmpty()) {
			Toast.makeText(this, R.string.compress_alert, Toast.LENGTH_SHORT)
					.show();
			return;
		}

		LayoutInflater factory = LayoutInflater.from(this);
		final View textEntryView = factory.inflate(
				R.layout.compress_dialog_text_entry, null);
		final EditText eText = (EditText) textEntryView
				.findViewById(R.id.filename_edit);

		if (fcbMarked.getFile(0).getName().length() >= 85) {
			eText.setText(Constant.textConvert(this, fcbMarked.getFile(0)
					.getName().substring(0, 81))
					+ Constant.ZIPENDSTRING);
			eText.setSelection(0,
					fcbMarked.getFile(0).getName().substring(0, 81).length());// modefied
																				// by
																				// PH
																				// 091123
		} else {
			eText.setText(Constant.textConvert(this, fcbMarked.getFile(0)
					.getName())
					+ Constant.ZIPENDSTRING);
			eText.setSelection(0, fcbMarked.getFile(0).getName().length());// modefied
																			// by
																			// PH
																			// 091123
		}
		eText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
				Constant.FILE_NAME_NUM_MAX) });

		new AlertDialog.Builder(this)
				.setTitle(R.string.alert_dialog_compress)
				.setView(textEntryView)
				.setPositiveButton(R.string.alert_dialog_ok,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								// inputMethodManager.hideSoftInputFromWindow(getListView().getWindowToken(),
								// 0);
								String name = eText.getText().toString();
								if (name.length() > 0
										&& name.length() <= Constant.FILE_NAME_NUM_MAX) {
									if (FileUtil.isNameUseable(name, false) == false) {
										Toast.makeText(FileBrowser.this,
												R.string.namebad,
												Toast.LENGTH_SHORT).show();
									} else {
										if (name.endsWith(Constant.ZIPENDSTRING) == false) {
											name += Constant.ZIPENDSTRING;
										}
										compressFile(name);
									}
								} else if (name.length() > Constant.FILE_NAME_NUM_MAX) {
									if (TAG_FLAG)
										Log.i(TAG,
												"$$$$$$$$$$$$$$$name.length()="
														+ name.length());
									Toast.makeText(FileBrowser.this,
											R.string.name_too_long,
											Toast.LENGTH_SHORT).show();// add
																		// by//
																		// PH//
																		// 091024
								} else {
									Toast.makeText(FileBrowser.this,
											R.string.nameempty,
											Toast.LENGTH_SHORT).show();
								}
							}

						})
				.setNegativeButton(R.string.alert_dialog_cancel,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								// User clicked cancel so do some stuff
							}
						}).show();
	}

	/*
	 * compress the selected file or directory in current directory
	 */
	private void compressFile(String rarname) {
		if (TAG_FLAG)
			Log.d(TAG, "==> compressFile");

		FileClipBoard fcbMarked = FileClipBoard.getInstance();
		fcbMarked.setOperation(FileClipBoard.OP_COMPRESS);
		if (TAG_FLAG)
			Log.i(TAG, "the number is " + String.valueOf(fcbMarked.getSize()));

		Bundle bundle = new Bundle();
		// bundle.putInt("request_code", Constant._COMPRESS);
		// bundle.putInt("srcfrom", Constant.FROM_CLIP);
		// bundle.putString("rarname", rarname);
		//
		// bundle.putString("toDir", currentDirectory.getPath());
		//
		// Intent intent = new Intent();
		// intent.setClass(this, FileCompressor.class);
		// intent.putExtras(bundle);
		// startActivityForResult(intent, Constant._COMPRESS);

		/*
		 * update 2010-11-1 xie
		 */
		if (TAG_FLAG)
			Log.d(TAG, "compress***********************compress");
		bundle.putInt(FileOp.KEY_INT_FOP_CODE, FileOp.FOP_COMPRESS);
		bundle.putInt(FileOp.KEY_INT_SRC_FROM, FileOp.SRC_FROM_CLIP);
		bundle.putString(FileOp.KEY_STRING_DEST_FILE_NAME, rarname);
		bundle.putString(FileOp.KEY_STRING_DEST_DIR_PATH,
				currentDirectory.getPath());
		FileOp.launchActivityToDo(this, bundle, FileOp.FOP_COMPRESS);
		if (TAG_FLAG)
			Log.d(TAG, "compress------------------------------compress");
		updateFlag = false; // add 2010-12-03 by xie
		openFlag = true; // add 2010-12-03 by xie
	}

	protected void getFileAttri(File file) {

		// Log.i(TAG,
		// "****************************** filesize = "+file.length());
		if (file.isFile() && !file.isHidden()) {
			fileNum++;
			fileSize += file.length();
			if (fileNum % 10 == 0)
				mAttributeThread.onAttributeResult();
			// return;
		} else if (file.isDirectory() && !file.isHidden()) {
			subDirNum++;
			if (subDirNum % 10 == 0)
				mAttributeThread.onAttributeResult();
			File[] files = file.listFiles();
			for (int i = 0; i < files.length; i++) {
				if (mAttributeThread != null && mAttributeThread.mStop) {
					break;
				}
				getFileAttri(files[i]);
			}
		}
		if (mAttributeThread != null && !mAttributeThread.mStop)
			mAttributeThread.onAttributeResult();
	}

	private String transferSize(long lSize) {
		String size;
		int iPoint;
		if (lSize < 1024) {
			size = lSize + "B";
		} else if (lSize < 1024 * 1024) {
			size = String.valueOf(lSize / 1024.0);
			iPoint = size.indexOf(".");
			size = size.substring(0, iPoint + 2) + "K";
		} else if (lSize < 1024 * 1024 * 1024) {
			size = String.valueOf(lSize / 1024.0 / 1024);
			iPoint = size.indexOf(".");
			size = size.substring(0, iPoint + 2) + "M";
		} else if (lSize < 1024L * 1024L * 1024L * 1024L) {
			// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%lSize_G="+lSize);
			size = String.valueOf(lSize / 1024.0 / 1024 / 1024);
			iPoint = size.indexOf(".");
			size = size.substring(0, iPoint + 2) + "G";
		} else if (lSize < 1024L * 1024L * 1024L * 1024L * 1024L) {
			// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%lSize_T="+lSize);
			size = String.valueOf(lSize / 1024.0 / 1024 / 1024 / 1024);
			iPoint = size.indexOf(".");
			size = size.substring(0, iPoint + 2) + "T";
		} else {
			// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%lSize_Unknown="+lSize);
			size = getString(R.string.filesizeunknown);
		}

		return size;
	}

	private void disAttri() {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%disAttri");
		subDirNum = -1;
		fileNum = 0;
		fileSize = 0;

		/*
		 * if (MarkedFile.isEmpty()) { Toast.makeText(this,
		 * R.string.error_file_does_not_exists, 3); return; }
		 */

		LayoutInflater factory = LayoutInflater.from(FileBrowser.this);
		View mtextEntryView = factory.inflate(R.layout.file_attri, null);
		TextView mFileName = (TextView) mtextEntryView
				.findViewById(R.id.filename);
		mSubDir = (TextView) mtextEntryView.findViewById(R.id.subdir);
		mSubFile = (TextView) mtextEntryView.findViewById(R.id.subfile);
		TextView mFileType = (TextView) mtextEntryView
				.findViewById(R.id.filetype);
		mTotalSize = (TextView) mtextEntryView.findViewById(R.id.totalsize);
		TextView mUpdateTime = (TextView) mtextEntryView
				.findViewById(R.id.updatetime);

		mAttributeThread = new MyAttributeThread(this) {
			public void run() {
				getFileAttri(MarkedFile.get(0));
			}
		};
		mAttributeThread.start();
		Date modifTime = new Date(MarkedFile.get(0).lastModified());
		String modiftime = DateFormat.getTimeFormat(getApplicationContext())
				.format(modifTime);
		String modifdate = DateFormat.getDateFormat(getApplicationContext())
				.format(modifTime);
		arrfilename = MarkedFile.get(0).getName();
		arrmodifyDate = modifdate + " " + modiftime;

		mFileName.setText(getResources().getString(R.string.filename)
				+ arrfilename);
		mUpdateTime.setText(getResources().getString(R.string.updatetime)
				+ arrmodifyDate);
		if (MarkedFile.get(0).isDirectory()) {
			mSubDir.setVisibility(View.VISIBLE);
			mSubFile.setVisibility(View.VISIBLE);
			mFileType.setVisibility(View.GONE);
		} else if (MarkedFile.get(0).isFile()) {
			mSubDir.setVisibility(View.GONE);
			mSubFile.setVisibility(View.GONE);
			mFileType.setVisibility(View.VISIBLE);

			int strId = R.string.unknownfile;
			if (checkEndsWithInStringArray(arrfilename, getResources()
					.getStringArray(R.array.fileEndingImage))) {
				strId = R.string.picturefile;
			} else if (checkEndsWithInStringArray(arrfilename, getResources()
					.getStringArray(R.array.fileEndingWebText))) {
				strId = R.string.htmlfile;
			} else if (checkEndsWithInStringArray(arrfilename, getResources()
					.getStringArray(R.array.fileEndingPackage))) {
				strId = R.string.compressfile;
			} else if (checkEndsWithInStringArray(arrfilename, getResources()
					.getStringArray(R.array.fileEndingAudio))) {
				strId = R.string.audiofile;
			} else if (checkEndsWithInStringArray(arrfilename, getResources()
					.getStringArray(R.array.fileEndingVideo))) {
				strId = R.string.videofile;
			} else if (checkEndsWithInStringArray(arrfilename, getResources()
					.getStringArray(R.array.fileEndingOffice))) {
				strId = R.string.Document;
			} else if (checkEndsWithInStringArray(arrfilename, getResources()
					.getStringArray(R.array.fileEndingAndroid))) {
				strId = R.string.android_file;
			} else if (FileUtil.getExtension(arrfilename).equals(".txt")) {
				strId = R.string.txt_file;
			} else if (FileUtil.getExtension(arrfilename).equals(".pdf")) {
				strId = R.string.pdf_file;
			} else if (FileUtil.getExtension(arrfilename).equals(".vcf")) {
				strId = R.string.vcf_file;
			} else if (FileUtil.getExtension(arrfilename).equals(".csv")) {
				strId = R.string.csv_file;
			}
			mFileType.setText(getResources().getString(R.string.filetype)
					+ getResources().getString(strId));
		}

		new AlertDialog.Builder(FileBrowser.this)
				.setTitle(R.string.alert_dialog_attribute)
				.setView(mtextEntryView)
				.setPositiveButton(R.string.alert_dialog_ok,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								if (mAttributeThread != null)
									mAttributeThread.toStop();
							}
						}).show();

	}

	private void unmarkallFile() {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%unmarkallFile");
		if (!MarkedFile.isEmpty()) {
			MarkedFile.clear();
			isSelected = false;
			// refreshScr();

			itemList.notifyDataSetChanged();
			// this.getListView().setAdapter(null);
			// this.getListView().setAdapter(itemSelect);
		}
	}

	/*
	 * make all files in the current directory checked
	 */
	private void markAllFile() {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%markAllFile");
		MarkedFile.clear();
		for (int i = 0; i < directoryEntries.size(); i++) {
			if (!directoryEntries.get(i).getFile().isHidden()) {
				MarkedFile.add(directoryEntries.get(i).getFile());
			}
		}
		isSelected = true;
		// refreshScr();
		itemList.notifyDataSetChanged();
	}

	/*
	 * open a dialog to list
	 */
	private void sendFile(File file) {
		FileShare.send(this, file);
	}

	private void onPaste() {
		FileClipBoard fcbMarked = FileClipBoard.getInstance();
		if (fcbMarked.hasValidData()) {
			if (fcbMarked.getOperation() == FileClipBoard.OP_COPY) {
				copyFile();
			} else if (fcbMarked.getOperation() == FileClipBoard.OP_CUT) {
				cutFile();
			}
		}

		updateFlag = false; // add 2010-11-27 by xie
	}

	private void cutFile() {
		Log.d(TAG, "==>cutFile");

		String toDir = "";
		File dir;

		FileClipBoard fcbMarked = FileClipBoard.getInstance();
		if (fcbMarked.isEmpty()) {
			// no files marked to copy
			Toast.makeText(this, R.string.nosource, Toast.LENGTH_SHORT).show();
		} else {
			// get the current path as the destination directory
			IconifiedText ob = (IconifiedText) mlvContent.getSelectedItem();
			if (ob != null) {
				if (TAG_FLAG)
					Log.d(TAG, "ob.getFile().getParent()11111=========="
							+ ob.getFile().getParent());
				// dir = new File(ob.getFile().getAbsolutePath());
				if (ob.getFile().isFile()) {
					toDir = ob.getFile().getParent();
				} else if (ob.getFile().isDirectory()) {
					toDir = currentDirectory.getPath();
				}
			} else {
				toDir = currentDirectory.getPath();
				if (TAG_FLAG)
					Log.d(TAG, "toDirtoDirtoDirtoDir=========="
							+ currentDirectory.getAbsolutePath());
				// dir = new File(toDir);
			}
		}

		for (int i = 0; i < MarkedFile.size(); i++) {
			if (!MarkedFile.get(i).isDirectory()) {
				continue;
			}
			if (toDir.equals(MarkedFile.get(i).getAbsolutePath())
					|| toDir.contains(MarkedFile.get(i).getAbsolutePath() + "/")) {// modified
																					// by
																					// PH
																					// 091113
				Toast.makeText(this, R.string.cantCutForSame,
						Toast.LENGTH_SHORT).show();
				return;
			}
		}
		// start a FIleMan activity to copy files
		// build an Intent and combine parameters for FileMan
		// Bundle bundle = new Bundle();
		// bundle.putInt("request_code", Constant._CUT);
		// bundle.putString("destination", toDir);
		// callFileManDoAction(bundle, Constant._CUT);

		/*
		 * update 2010-11-1 xie
		 */
		if (TAG_FLAG)
			Log.d(TAG, "cut******************************cut");
		Bundle bundle = new Bundle();
		bundle.putInt(FileOp.KEY_INT_FOP_CODE, FileOp.FOP_CUT);
		bundle.putString(FileOp.KEY_STRING_DEST_DIR_PATH, toDir);
		FileOp.launchActivityToDo(this, bundle, FileOp.FOP_CUT);
		if (TAG_FLAG)
			Log.d(TAG, "cut-------------------------------cut");

	}

	private void copyFile() {
		if (TAG_FLAG)
			Log.d(TAG, " ==> copyFile");
		String toDir = "";
		// File dir;

		FileClipBoard fcbMarked = FileClipBoard.getInstance();
		if (fcbMarked.isEmpty()) {
			Toast.makeText(FileBrowser.this, R.string.nosource, 3).show();
			return;
		}

		// define the destination
		IconifiedText ob = (IconifiedText) mlvContent.getSelectedItem();
		if (ob != null) {
			if (ob.getFile().isFile()) {
				toDir = ob.getFile().getParent();
			} else if (ob.getFile().isDirectory()) {
				toDir = currentDirectory.getPath();
			}
		} else {
			toDir = currentDirectory.getPath();
		}

		// if the destination is not a directory, then get its parent directory
		// check if destination dir is a child dir
		// check if we copy the parent dir to child dir
		for (int i = 0; i < fcbMarked.getSize(); i++) {
			if (!fcbMarked.getFile(i).isDirectory()) {
				continue;
			}
			if (toDir.equals(fcbMarked.getFile(i).getAbsolutePath())
					|| toDir.contains(fcbMarked.getFile(i).getAbsolutePath()
							+ "/")) {// modified by PH 091113
				Toast.makeText(this, R.string.cantCopyForSame, 3).show();
				return;
			}
		}

		// start a FileMan activity to copy files
		// build an Intent and combine parameters for FileMan
		// Log.i(TAG, "******************** MarkedFile="+MarkedFile);
		// Bundle bundle = new Bundle();
		// bundle.putInt("request_code", Constant._COPY);
		// bundle.putString("destination", toDir);
		//
		// callFileManDoAction(bundle, Constant._COPY);

		/*
		 * UPDATE 2010-11-01 xie
		 */
		if (TAG_FLAG)
			Log.d(TAG, "COPY**********************COPY");
		Bundle bundle = new Bundle();
		bundle.putInt(FileOp.KEY_INT_FOP_CODE, FileOp.FOP_COPY);
		bundle.putString(FileOp.KEY_STRING_DEST_DIR_PATH, toDir);
		callFileManDoAction(bundle, FileOp.FOP_COPY);
		if (TAG_FLAG)
			Log.d(TAG, "COPY---------------------COPY");
	}

	private void callFileManDoAction(Bundle bundle, int action) {
		// Intent intent = new Intent();
		// intent.setClass(this, FileMan.class);
		// intent.putExtras(bundle);
		// startActivityForResult(intent, action);

		/*
		 * update 2010-11-01 xie
		 */
		FileOp.launchActivityToDo(this, bundle, action);
	}

	private void onRename(File file) {
		if (TAG_FLAG)
			Log.i(TAG, "==> onRename");

		FileHandler.MsgHandler handler = new FileHandler.MsgHandler(
				FileRename.MSG_RES_OK, new MsgHandleFunc() {
					// @Override
					public boolean onMessage(Message msg) {
						// TODO Auto-generated method stub
						browseTo(currentDirectory);
						return false;
					}
				});

		addMsgHandler(handler);
		FileRename.renameFile(this, file);
	}

	/*
	 * update delFile 2010-11-2 xie
	 */
	// private void delFile(){
	// protectSysDir();
	// if (MarkedFile.isEmpty()) {
	// Toast.makeText(this, R.string.error_file_does_not_exists, 3);
	// return;
	// }
	//
	// FileClipBoard fcbMarked = FileClipBoard.getInstance();
	// fcbMarked.clear();
	// fcbMarked.setOperation(FileClipBoard.OP_DELETE);
	// for (int i = 0; i < MarkedFile.size(); i++) {
	// File file = MarkedFile.get(i);
	// if (!fcbMarked.hasIt(file)) {
	// fcbMarked.addFile(file);
	// }
	// }
	// Log.i(TAG, "the marked files is " + MarkedFile.size());
	// Bundle bundle=new Bundle();
	// bundle.putInt(FileOp.KEY_INT_FOP_CODE, FileOp.FOP_DELETE);
	// bundle.putInt(FileOp.KEY_INT_SRC_FROM, FileOp.SRC_FROM_CLIP);
	// callFileManDoAction(bundle, FileOp.FOP_DELETE);
	// Log.i(TAG, "delFile-----------------------------------------delFile");
	//
	// }
	private void delFile() {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%delFile");
		// add by xieqm 110418
		if (null != MarkedFile) {
			String[] filePath = new String[MarkedFile.size()];
			for (int i = 0; i < MarkedFile.size(); i++) {
				filePath[i] = MarkedFile.get(i).getAbsolutePath();
				boolean isdownLoadOver = isFileDownLoadOver(filePath[i]);
				boolean isupLoadOver = isFileUpLoadOver(filePath[i]);
//				if (!isdownLoadOver) {// NetDiskManager.isDownLoadWork(filePath[i])
//					Log.d(TAG, "==> isDownLoadWork");
//					ErrorMessageDialog.showMessageDialog(FileBrowser.this,
//							getString(R.string.download_no_finish));
//					break;
//				} else if (!isupLoadOver) {// NetDiskManager.isUpLoadWork(filePath[i])
//					Log.d(TAG, "==> isUpLoadWork");
//					ErrorMessageDialog.showMessageDialog(FileBrowser.this,
//							getString(R.string.upload_no_finish));
//					break;
//				} else {
//					deleteFile();
//					break;
//				}
				
				if (!isdownLoadOver || !isupLoadOver) {// NetDiskManager.isDownLoadWork(filePath[i]))
					Log.d(TAG, "==> isDownLoadWork");
					ErrorMessageDialog.showMessageDialog(FileBrowser.this,
							getString(R.string.upload_or_download_now));
					break;
				} else {
					deleteFile();
					break;
				}
			}
			
			
		}
		// end
	}

	private void deleteFile() {
		protectSysDir();
		if (MarkedFile.isEmpty()) {
			Toast.makeText(FileBrowser.this,
					R.string.error_file_does_not_exists, 3);
			return;
		}

		// added by wuqf 2010-10-21
		FileHandler.MsgHandler handler = new FileHandler.MsgHandler(
				FileDelete.MSG_RES_OK, new MsgHandleFunc() {
					public boolean onMessage(Message msg) {
						// TODO Auto-generated method stub
						if (TAG_FLAG)
							Log.d("wuqf",
									"&&&&&&&&&&&******** has finish delete &&&&&&&&&&&&&********");
						State = _LIST;
						initState();
						if (TAG_FLAG)
							Log.d(TAG, "currentDirectory============="
									+ currentDirectory);
						browseTo(currentDirectory);
						// refreshData();
						// updateUI();
						return false;
					}
				});
		addMsgHandler(handler);

		handler = new FileHandler.MsgHandler(FileDelete.MSG_RES_CANCEL,
				new MsgHandleFunc() {
					public boolean onMessage(Message msg) {
						Toast.makeText(FileBrowser.this, // update 2010-12-08 by
															// xqm
								R.string.cancelOpration, Toast.LENGTH_SHORT)
								.show();
						return false;
					}
				});
		addMsgHandler(handler);

		if (MarkedFile.size() == 1) {
			FileDelete.deleteOneFile(this, MarkedFile.get(0));
		} else if (MarkedFile.size() > 1) {
			if (TAG_FLAG)
				Log.d("wuqf",
						"&&&&&&&&&&&&& marked file count: " + MarkedFile.size());
			FileClipBoard.getInstance().clear();
			FileClipBoard.getInstance().setOperation(FileClipBoard.OP_DELETE);
			for (int i = 0; i < MarkedFile.size(); i++) {
				File file = MarkedFile.get(i);
				if (!FileClipBoard.getInstance().hasIt(file)) {
					FileClipBoard.getInstance().addFile(file);
				}
			}
			FileDelete.deleteFilesInClip(this);
		}
		// end
	}

	/*
	 * create a new directory with a inputed name
	 * 
	 * @param filename - the name of the new directory
	 */
	private void creatDir(String filename) {
		if (TAG_FLAG)
			Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%creatDir");
		StatFs sf;
		sf = new StatFs(DirDefines.mDir1);// Constant.sdroot
		if (((long) sf.getAvailableBlocks() * sf.getBlockSize()) < (long) 10 * 1024) {
			new AlertDialog.Builder(this)
					.setTitle(R.string.remind)
					.setMessage(R.string.nospaceonsd)
					.setPositiveButton(R.string.alert_dialog_ok,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
								}
							}).show();
		} else {
			String parent = "";
			parent = currentDirectory.getPath();
			// can not create a directory under a file
			if (new File(parent).isFile())
				return;
			// Log.i("FileBrowser",
			// "******************createDir1*****************");
			// Intent intent = new Intent();
			// intent.setClass(FileBrowser.this, FileMan.class);
			// Bundle bundle = new Bundle();
			// Log.d(TAG, "createDir11111111111111111111111createDir");
			// bundle.putInt("request_code", Constant._CREATEDIR);
			// bundle.putString("parent path", parent);
			// bundle.putString("file name", filename);
			// intent.putExtras(bundle);
			// startActivityForResult(intent, Constant._CREATEDIR);

			/*
			 * update 2010-11-1 xie
			 */
			if (TAG_FLAG)
				Log.d(TAG, "createDir*********************createDir");
			Bundle bundle = new Bundle();
			bundle.putInt(FileOp.KEY_INT_FOP_CODE, FileOp.FOP_CREATE_DIR);
			bundle.putString(FileOp.KEY_STRING_DEST_DIR_PATH, parent);
			bundle.putString(FileOp.KEY_STRING_DEST_FILE_NAME, filename);
			FileOp.launchActivityToDo(this, bundle, FileOp.FOP_CREATE_DIR);
			if (TAG_FLAG)
				Log.d(TAG, "createDir------------------------------createDir");

			updateFlag = false; // add 2010-12-03 by xie
			openFlag = true; // add 2010-12-03 by xie
		}
	}

	// add by PH 091013
	private void createOffice(String filename) {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%createOffice");
		StatFs sf;
		sf = new StatFs(DirDefines.mDir1);// Constant.sdroot
		if (((long) sf.getAvailableBlocks() * sf.getBlockSize()) < (long) 20 * 1024) {
			new AlertDialog.Builder(this)
					.setTitle(R.string.remind)
					.setMessage(R.string.nospaceonsd)
					.setPositiveButton(R.string.alert_dialog_ok,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
								}
							}).show();
		} else {
			String parent = "";
			parent = currentDirectory.getPath();
			// can not create a directory under a file
			if (new File(parent).isFile())
				return;
			// Log.i("FileBrowser","******************createOffice1*****************");
			// Intent intent = new Intent();
			// intent.setClass(FileBrowser.this, FileMan.class);
			// Bundle bundle = new Bundle();
			// bundle.putInt("request_code", Constant._CREATEFILE);
			// bundle.putString("parent path", parent);
			// bundle.putString("file name", filename);
			// intent.putExtras(bundle);
			// startActivityForResult(intent, Constant._CREATEFILE);
			if (TAG_FLAG)
				Log.d(TAG, "createOffice*********************createOffice");
			Bundle bundle = new Bundle();
			bundle.putInt(FileOp.KEY_INT_FOP_CODE, FileOp.FOP_CREATE_FILE);
			bundle.putString(FileOp.KEY_STRING_DEST_DIR_PATH, parent);
			bundle.putString(FileOp.KEY_STRING_DEST_FILE_NAME, filename);
			Log.i(TAG, "the file name is " + filename);
			FileOp.launchActivityToDo(this, bundle, FileOp.FOP_CREATE_FILE);
			if (TAG_FLAG)
				Log.d(TAG,
						"createOffice------------------------------createOffice");

			updateFlag = false; // add 2010-12-03 by xie
			openFlag = true; // add 2010-12-03 by xie
		}
	}

	// end PH 091013

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%onActivityResult");
		// clear all marked files
		// this.unmarkallFile();

		if (!MarkedFile.isEmpty()) {
			MarkedFile.clear();
			isSelected = false;
		}
		isSelected = false;
		cut_copy = false;

		switch (requestCode) {
		case Constant._ATTRIDISPLAY:
			switch (resultCode) {
			case RESULT_OK:
				/* get response form FileMan */
				Bundle bundle = data.getExtras();
				// TODO display the returned attributes
				LayoutInflater factory = LayoutInflater.from(this);
				final View textEntryView = factory.inflate(R.layout.file_attri,
						null);

				TextView tv = (TextView) textEntryView
						.findViewById(R.id.filename);
				String mfileName = bundle.getString("ARRFILENAME");
				tv.setText(this.getResources().getString(R.string.filename)
						+ mfileName);

				tv = (TextView) textEntryView.findViewById(R.id.subdir);
				String nDir = bundle.getString("ARRSUBDIR");
				if (nDir == null || nDir.length() == 0) {
					tv.setVisibility(View.GONE);
				} else {
					tv.setText(this.getResources().getString(R.string.subdir)
							+ nDir);
				}

				tv = (TextView) textEntryView.findViewById(R.id.subfile);
				String nFile = bundle.getString("ARRFILENUM");
				if (nFile == null || nFile.length() == 0) {
					tv.setVisibility(View.GONE);

					int strId = R.string.unknownfile;
					if (checkEndsWithInStringArray(mfileName, getResources()
							.getStringArray(R.array.fileEndingImage))) {
						strId = R.string.picturefile;
					} else if (checkEndsWithInStringArray(
							mfileName,
							getResources().getStringArray(
									R.array.fileEndingWebText))) {
						strId = R.string.htmlfile;
					} else if (checkEndsWithInStringArray(
							mfileName,
							getResources().getStringArray(
									R.array.fileEndingPackage))) {
						strId = R.string.compressfile;
					} else if (checkEndsWithInStringArray(
							mfileName,
							getResources().getStringArray(
									R.array.fileEndingAudio))) {
						strId = R.string.audiofile;
					} else if (checkEndsWithInStringArray(
							mfileName,
							getResources().getStringArray(
									R.array.fileEndingVideo))) {
						strId = R.string.videofile;
					} else if (checkEndsWithInStringArray(
							mfileName,
							getResources().getStringArray(
									R.array.fileEndingOffice))) {
						strId = R.string.Document;
					} else if (checkEndsWithInStringArray(
							mfileName,
							getResources().getStringArray(
									R.array.fileEndingAndroid))) {
						strId = R.string.android_file;
					} else if (FileUtil.getExtension(mfileName).equals(".txt")) {
						strId = R.string.txt_file;
					} else if (FileUtil.getExtension(mfileName).equals(".pdf")) {
						strId = R.string.pdf_file;
					} else if (FileUtil.getExtension(mfileName).equals(".vcf")) {
						strId = R.string.vcf_file;
					} else if (FileUtil.getExtension(mfileName).equals(".csv")) {
						strId = R.string.csv_file;
					}

					tv = (TextView) textEntryView.findViewById(R.id.filetype);
					tv.setText(this.getResources().getString(R.string.filetype)
							+ getResources().getString(strId));
				} else {
					tv.setText(this.getResources().getString(R.string.filenum)
							+ nFile);
					tv = (TextView) textEntryView.findViewById(R.id.filetype);
					tv.setVisibility(View.GONE);
				}
				tv = (TextView) textEntryView.findViewById(R.id.totalsize);
				String size = bundle.getString("ARRTOTALFILESIZE");
				tv.setText(this.getResources().getString(R.string.totalsize)
						+ size);

				if (bundle.getString("ARRMODIRYDATE") != null) {
					tv = (TextView) textEntryView.findViewById(R.id.updatetime);
					String uTime = bundle.getString("ARRMODIRYDATE");
					tv.setText(this.getResources().getString(
							R.string.updatetime)
							+ uTime);
				}

				new AlertDialog.Builder(FileBrowser.this)
						.setTitle(R.string.alert_dialog_attribute)
						.setView(textEntryView)
						.setPositiveButton(R.string.alert_dialog_ok,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
									}
								}).show();
				break;
			}
			break;
		case Constant._SEARCH:
			switch (resultCode) {
			case RESULT_OK:
				// get response form FileMan
				boolean flag = data.getExtras().getBoolean("dirFlag");
				if (flag) {
					String toDir = data.getExtras().getString("destination");
					this.browseTo(new File(toDir));
				} else {
					searchDecom = true;
					searchFile = (File) data.getExtras()
							.getSerializable("FILE");
					searchpath = data.getExtras().getString("PATH");
					searchpathnofile = data.getExtras().getString("PATHNOFILE");
					FileManagerOpenFile(searchFile, this);
					// this.browseTo(new File(searchpathnofile));
				}
				break;
			}
			break;
		case Constant._CUT:
			switch (resultCode) {
			case RESULT_OK:
				// Log.i(TAG,
				// "111111111111111111111111111111222222222222222222222222222222222");
				mlvContent.setAdapter(null);
				mlvContent.setAdapter(itemList);
			}

			/*
			 * refresh ui 2010-11-3 xie
			 */
		case FileOp.FOP_DELETE:
			switch (resultCode) {
			case RESULT_OK:
				if (TAG_FLAG)
					Log.i(TAG, "delete-----------refresh");
				State = _LIST;
				initState();
			}

		case FileOp.FOP_CREATE_DIR:
		case FileOp.FOP_CREATE_FILE:
			if (TAG_FLAG)
				Log.i(TAG, "return after create!!!");
			if (RESULT_OK == resultCode) {
				String newPath = data.getStringExtra("NEW_FILE");
				if (null == newPath) {
					Log.e(TAG, "newPath in bundle is null in onActivityResult");
				} else {
					File file = new File(newPath);
					if (null == file || !file.exists()) {
						Log.e(TAG, "newPath is invalid in onActivityResult");
					} else {
						Drawable fileIcon = FileUtil.getDefaultIconForFile(
								this, file);
						directoryEntries.add(new IconifiedText(fileIcon, file,
								false));
						itemList.setListItems(directoryEntries);
						itemList.notifyDataSetChanged();
					}
				}
			}
			break;
		case FileOp.FOP_COMPRESS:
			if (TAG_FLAG)
				Log.i(TAG, "return after compress!!!");
			if (RESULT_OK == resultCode) {
				String newPath = data.getStringExtra("NEW_FILE");
				if (null == newPath) {
					Log.e(TAG, "newPath in bundle is null in onActivityResult");
				} else {
					File file = new File(newPath);
					if (null == file || !file.exists()) {
						Log.e(TAG, "newPath is invalid in onActivityResult");
					} else {
						boolean isExisted = false;
						for (IconifiedText it : directoryEntries) {
							if (it.getFile().equals(file)) {
								isExisted = true;
								break;
							}
						}
						if (!isExisted) {
							if (TAG_FLAG)
								Log.i(TAG, "add new file at end");
							Drawable fileIcon = FileUtil.getDefaultIconForFile(
									this, file);
							if (file.getName().contains(ZIPENDSTRING)) {
								fileIcon = getResources().getDrawable(
										R.drawable.zip);
							}
							directoryEntries.add(new IconifiedText(fileIcon,
									file, false));
							itemList.setListItems(directoryEntries);
							itemList.notifyDataSetChanged();
						}
					}
				}
			}
			break;
		case FileOp.FOP_DECOMPRESS:
		case FileOp.FOP_COPY:
		case FileOp.FOP_CUT:
			Log.i(TAG, "return after decompress!!!");
			if (RESULT_OK == resultCode) {
				ArrayList<String> newFiles = data
						.getStringArrayListExtra("NEW_FILES");
				if (null == newFiles || 0 == newFiles.size()) {
					if (TAG_FLAG)
						Log.e(TAG, "invalid NEW_FILES value in intent");
				} else {
					ListIterator<IconifiedText> iterator = directoryEntries
							.listIterator();

					// remove the replaced files in old item list
					while (iterator.hasNext()) {
						IconifiedText it = iterator.next();
						String oldPath = it.getFile().getAbsolutePath();
						if (newFiles.contains(oldPath))
							iterator.remove();
					}
					if (TAG_FLAG)
						Log.i(TAG, "the new file size is " + newFiles.size());

					for (String path : newFiles) {
						File file = new File(path);

						if (null == file || !file.exists()) {
							if (TAG_FLAG)
								Log.e(TAG,
										"newPath is invalid in onActivityResult");
						} else {
							Drawable fileIcon = FileUtil.getDefaultIconForFile(
									this, file);
							if (file.getName().contains(ZIPENDSTRING)) {
								fileIcon = getResources().getDrawable(
										R.drawable.zip);
							}
							directoryEntries.add(new IconifiedText(fileIcon,
									file, false));
						}
						itemList.setListItems(directoryEntries);
						itemList.notifyDataSetChanged();
					}
				}
				if (TAG_FLAG) {
					Log.i(TAG, "the updateFlag is " + updateFlag);
					Log.i(TAG, "the openFlag is " + openFlag);
				}
			}
			break;
		default:
			break;

		}
	}

	public void exit() {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%exit");
		System.exit(0);
	}

	/*
	 * check whether the system directories are selected,if so remove them from
	 * MarkedFile list call this method before cut,delete and rename to protect
	 * system directories
	 * 
	 * @return true,if a system directory is selected; otherwise,return false.
	 */

	/*
	 * add 2010-11-4 xie
	 */
	private void protectSysDir() {
		if (TAG_FLAG)
			Log.d(TAG, "protectSysDir");
		boolean hasSysDir = false;
		String alertStr = null;
		// List<File> sysList = getSysDir();
		List<File> removeList = new ArrayList<File>();
		removeList.clear();
		if (MarkedFile.isEmpty())
			return;
		else {
			for (int i = 0; i < MarkedFile.size(); i++) {
				if (Constant.isSysOrReservedDir(this, MarkedFile.get(i))) {
					hasSysDir = true;
					removeList.add(MarkedFile.get(i));

					if (alertStr == null)
						alertStr = Constant.textConvert(this, MarkedFile.get(i)
								.getName());
					else
						alertStr += ", "
								+ Constant.textConvert(this, MarkedFile.get(i)
										.getName());
				}

			}
		}
		// added by wuqf
		if (hasSysDir == true) {
			if (cut_copy) {
				alertStr += getResources().getString(R.string.cut_alert);
				Toast.makeText(FileBrowser.this, alertStr, Toast.LENGTH_SHORT)
						.show();
			}
		}
		// end
		if (!removeList.isEmpty())
			MarkedFile.removeAll(removeList);
	}

	// ////////////

	private boolean isNameUseable(String name, boolean isDerectory) {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%isNameUseable");
		// /\:?<>"|*.'
		boolean ret = false;
		if (name.length() > 0) {
			if (name.startsWith(".") == false
			/* && name.startsWith(" ") == false */
			&& name.contains("/") == false && name.contains("\\") == false
					&& name.contains(":") == false
					&& name.contains("?") == false
					&& name.contains("？") == false
					&& name.contains("<") == false
					&& name.contains(">") == false
					&& name.contains("\"") == false
					&& name.contains("|") == false
					&& name.contains("*") == false
					// && ((isDerectory==true)?(name.contains(".") ==
					// false):true)
					&& name.contains("'") == false) {
				ret = true;
			}
		}

		return ret;
	}

	public void onTitleIconClick() {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%onTitleIconClick");
		if (State == _SELECT) {
			// select2list();
			State = _LIST;
			initState();
		} else if (State == _LIST) {
			String parent = this.currentDirectory.getAbsolutePath();
			if (TAG_FLAG) {
				Log.i(TAG, "the parent is " + parent);
				Log.i(TAG, "the root is " + root);
			}
			if (parent != null && !parent.equals(root)) {
				upOneLevel();
			} else if (parent != null && parent.equals(root)) {
				Log.i(TAG, "quit fm");
				Intent intent = new Intent();
				intent.setClass(FileBrowser.this, TdActivity.class);
				intent.putExtra("projectState", projectState);
				startActivity(intent);
				finish();
				// initState();
				// browseToRoot();
				// mlvContent.setSelection(0);
			}
		}
	}

	private BroadcastReceiver SdCardIntentReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (TAG_FLAG)
				Log.d(TAG, "#################### SDaction = " + action);
			if (action.equals(Intent.ACTION_MEDIA_SHARED)) {
				if (browsetoThreadFlag)
					mProgressDialog.dismiss();
				if (!mToCloseSend) {
					new AlertDialog.Builder(FileBrowser.this)
							.setMessage(R.string.sd_shared)
							.setPositiveButton(R.string.alert_dialog_ok,
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int which) {
											finish();
										}
									}).show()
							.setOnDismissListener(new OnDismissListener() {
								public void onDismiss(DialogInterface dialog) {
									// TODO Auto-generated method stub
									finish();
								}
							});
					mToCloseSend = true;
				}
			} else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
				if (TAG_FLAG)
					Log.d(TAG, "********************"
							+ Intent.ACTION_MEDIA_MOUNTED);
				getWindow().addFlags(
						WindowManager.LayoutParams.FLAG_ROCKET_MENU_NOTIFY);
				btnSD.setVisibility(View.VISIBLE);
				btnSearch.setVisibility(View.VISIBLE);
				editText.setVisibility(View.VISIBLE);
				tv.setVisibility(View.VISIBLE);
				if (directoryEntries.size() == 0) {
					nothing = true;
					t.setText(R.string.not_found);
					t.setVisibility(View.VISIBLE);
				} else {
					nothing = false;
					t.setVisibility(View.GONE);
				}
				mlvContent.setVisibility(View.VISIBLE);
				sdRemoved = false;
				if (TAG_FLAG)
					Log.d(TAG, "#################" + currentDirectory.getPath());
				browseTo(currentDirectory);
			} else if (action.equals(Intent.ACTION_MEDIA_UNMOUNTABLE)) {
				btnSD.setVisibility(View.GONE);
				btnSearch.setVisibility(View.GONE);
				editText.setVisibility(View.GONE);
				tv.setVisibility(View.GONE);
				t.setVisibility(View.VISIBLE);
				mlvContent.setVisibility(View.GONE);
				t.setText(R.string.sd_corrupted);
			} else if (action.equals(Intent.ACTION_MEDIA_UNMOUNTED)) {
				btnSD.setVisibility(View.GONE);
				btnSearch.setVisibility(View.GONE);
				editText.setVisibility(View.GONE);
				tv.setVisibility(View.GONE);
				t.setVisibility(View.VISIBLE);
				mlvContent.setVisibility(View.GONE);
				t.setText(R.string.sd_unmounted);
			} else if (action.equals(Intent.ACTION_MEDIA_BAD_REMOVAL)) {
				btnSD.setVisibility(View.GONE);
				btnSearch.setVisibility(View.GONE);
				editText.setVisibility(View.GONE);
				tv.setVisibility(View.GONE);
				t.setVisibility(View.VISIBLE);
				mlvContent.setVisibility(View.GONE);
				t.setText(R.string.sd_bad_removal);
			} else if (action.equals(Intent.ACTION_MEDIA_NOFS)) {
				btnSD.setVisibility(View.GONE);
				btnSearch.setVisibility(View.GONE);
				editText.setVisibility(View.GONE);
				tv.setVisibility(View.GONE);
				t.setVisibility(View.VISIBLE);
				mlvContent.setVisibility(View.GONE);
				t.setText(R.string.sd_nofs);
			} else if (action.equals(Intent.ACTION_MEDIA_CHECKING)) {
				btnSD.setVisibility(View.GONE);
				btnSearch.setVisibility(View.GONE);
				editText.setVisibility(View.GONE);
				tv.setVisibility(View.GONE);
				t.setVisibility(View.VISIBLE);
				mlvContent.setVisibility(View.GONE);
				t.setText(R.string.sd_disk_checking);
			}
		}
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%onKeyDown");
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK: {
			onTitleIconClick();
			return true;
		}
		}
		return super.onKeyDown(keyCode, event);
	}

	private void switchingDirectory() {
		IntentFilter commandFilters = new IntentFilter();
		commandFilters.addAction(Intent.ACTION_MEDIA_MOUNTED);
		commandFilters.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
		commandFilters.addAction(Intent.ACTION_MEDIA_REMOVED);
		commandFilters.addAction(Intent.ACTION_MEDIA_SHARED);
		commandFilters.addAction(Intent.ACTION_MEDIA_UNMOUNTABLE);
		commandFilters.addAction(Intent.ACTION_MEDIA_CHECKING);
		commandFilters.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
		commandFilters.addAction(Intent.ACTION_MEDIA_NOFS);
		commandFilters.addDataScheme("file");
		registerReceiver(sdCardIntentReceiver, commandFilters);
		mReceiver = true;

		layout = (LinearLayout) getLayoutInflater().inflate(
				R.layout.dir_dialog_list, null);
		sdcardText = (TextView) layout.findViewById(R.id.sdcardText);
		phoneLayout = (LinearLayout) layout.findViewById(R.id.phoneLayout);
		sdcardLayout = (LinearLayout) layout.findViewById(R.id.sdcardLayout);
		lenovoLayout = (LinearLayout) layout.findViewById(R.id.lenovoLayout);
		phoneLayout.setOnTouchListener(this);
		sdcardLayout.setOnTouchListener(this);
		lenovoLayout.setOnTouchListener(this);
		phoneLayout.setOnClickListener(FileBrowser.this);
		lenovoLayout.setOnClickListener(FileBrowser.this);
		if (sdCardtatus.equals(Environment.MEDIA_SHARED)
				|| sdCardtatus.equals(Environment.MEDIA_UNMOUNTED)
				|| sdCardtatus.equals(Environment.MEDIA_CHECKING)) {
			if (projectState.equals(DirDefines.mDir1)) {
				sdcardText.setTextColor(android.graphics.Color.GRAY);
				sdcardLayout.setEnabled(false);
			} else if (projectState.equals(DirDefines.mDir3)) {
				sdcardLayout.setVisibility(View.GONE);
			}
		} else {
			if (projectState.equals(DirDefines.mDir1)) {
				sdcardText.setTextColor(android.graphics.Color.WHITE);
				sdcardLayout.setEnabled(true);
				sdcardLayout.setOnClickListener(this);
			} else if (projectState.equals(DirDefines.mDir3)) {
				sdcardLayout.setVisibility(View.GONE);
			}
		}
		dialog = new AlertDialog.Builder(FileBrowser.this)
				.setTitle(R.string.switching_directory)
				.setView(layout)
				.setPositiveButton(R.string.alert_dialog_cancel,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
							}
						}).show();
	}

	private void loginLenovo() {
		if (null != dialog) {
			dialog.cancel();
		}
		mndManager = NetDiskManager.getInstance(this);
		if (null == NetDiskConstant.NET_DISK_ROOT) {
			Log.d(TAG, "net disk is null");

			ProgressMessageDialog.showMessageDialog(this,
					getString(R.string.login), getString(R.string.loading));

			mndManager.bindOpService();

			LoginThread mThread = new LoginThread(this) {
				public void run() {

					long id = -1;
					while (true) {
						if (mndManager.isConnected()) {
							id = mndManager.login("xiexie_0101@163.com",
									"123456");
							break;
						} else {
							try {
								Thread.sleep(200);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
					}

					NetDiskOpResult result = null;

					do {
						try {
							Thread.sleep(100);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}

						result = mndManager.getResult(id);

						if (null != result)
							break;
					} while (true);

					NetFile nfRoot = null;

					try {
						nfRoot = result.GetRootNetFile();
					} catch (JSONException e) {
						e.printStackTrace();
					}

					if (null != nfRoot) {
						NetDiskConstant.NET_DISK_ROOT = nfRoot;
						Log.e(TAG, "the root id is " + nfRoot.getID());
						onLoginOk();
					} else {
						mHandler.post(new Runnable() {

							@Override
							public void run() {
								String errorMsg = NetDiskOpResult
										.strGetErrorMsg();
								if (TAG_FLAG) {
									Log.d(TAG,
											"the errorMsg is ================ "
													+ errorMsg);
									AlertDialog dialog = new AlertDialog.Builder(
											FileBrowser.this)
											.setTitle(
													R.string.switching_directory)
											.setTitle(R.string.remind)
											.setMessage(errorMsg)
											.setPositiveButton(
													R.string.dlg_btn_ok,
													new DialogInterface.OnClickListener() {

														@Override
														public void onClick(
																DialogInterface dialog,
																int which) {
															dialog.cancel();
															ProgressMessageDialog
																	.cancelDialog();
														}
													}).show();
								}
							}
						});
					}

				}
			};

			mThread.start();
		} else {
			if (TAG_FLAG) {
				Log.d(TAG, "net disk is not null");
				Log.d(TAG, "the isUpload is =================== " + isUpload);
			}
			if (isUpload) {
				Intent intent = new Intent();
				String mUpload = DirDefines.UPLOAD;
				intent.putExtra("projectState", projectState);
				mUpload = DirDefines.UPLOAD;
				intent.putExtra("mUpload", mUpload);
				intent.putExtra("uploadFile", uploadFile);
				intent.putExtra("uploadFileTypes", uploadFileTypes);
				intent.setClass(
						FileBrowser.this,
						com.lenovo.leos.filebrowser.netdisk.LenovoInterfaceActivity.class);
				startActivity(intent);
				return;
			} else{
				Intent intent = new Intent();
				intent.setClass(
						FileBrowser.this,
						com.lenovo.leos.filebrowser.netdisk.LenovoActivity.class);
				intent.putExtra("projectState", projectState);
				startActivity(intent);
				finish();
			}
		}
	}

	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		if (TAG_FLAG) {
			Log.d(TAG, "projectState=================" + projectState);
		}
		Intent intent = new Intent();
		if (DirDefines.mDir1.equals(projectState)) {
			switch (view.getId()) {
			case R.id.phoneLayout:
				Toast.makeText(FileBrowser.this, "访问手机接口", Toast.LENGTH_SHORT)
						.show();
				intent.putExtra("projectState", projectState);
				intent.setClass(FileBrowser.this, FileBrowser.class);
				startActivity(intent);
				finish();
				break;
			case R.id.sdcardLayout:
				Toast.makeText(FileBrowser.this, "SD卡", Toast.LENGTH_SHORT)
						.show();
				intent.putExtra("projectState", projectState);
				intent.setClass(FileBrowser.this, FileBrowser.class);
				startActivity(intent);
				finish();
				break;
			case R.id.lenovoLayout:
				loginLenovo();
				break;
			}
		} else if (DirDefines.mDir3.equals(projectState)) {
			switch (view.getId()) {
			case R.id.phoneLayout:
				Toast.makeText(FileBrowser.this, "访问手机接口", Toast.LENGTH_SHORT)
						.show();
				intent.putExtra("projectState", projectState);
				intent.setClass(FileBrowser.this,
						com.lenovo.leos.filebrowser.ui.FileBrowser.class);
				startActivity(intent);
				finish();
				break;
			case R.id.lenovoLayout:
				loginLenovo();
				break;

			}
		}
	}

	private BroadcastReceiver sdCardIntentReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (TAG_FLAG)
				Log.d(TAG, "#################### SDaction = " + action);
			if (DirDefines.mDir1.equals(projectState)) {
				if (action.equals(Intent.ACTION_MEDIA_SHARED)
						|| action.equals(Intent.ACTION_MEDIA_UNMOUNTABLE)
						|| action.equals(Intent.ACTION_MEDIA_UNMOUNTED)
						|| action.equals(Intent.ACTION_MEDIA_BAD_REMOVAL)
						|| action.equals(Intent.ACTION_MEDIA_NOFS)
						|| action.equals(Intent.ACTION_MEDIA_CHECKING)
						|| action.equals(Intent.ACTION_MEDIA_REMOVED)) {
					sdcardText.setEnabled(false);
					sdcardText.setTextColor(android.graphics.Color.GRAY);
				} else {
					sdcardText.setEnabled(true);
					sdcardText.setTextColor(android.graphics.Color.WHITE);
					sdcardLayout.setOnClickListener(FileBrowser.this);
				}
			}
		}
	};

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			phoneLayout
					.setBackgroundResource(android.R.drawable.list_selector_background);
			sdcardLayout
					.setBackgroundResource(android.R.drawable.list_selector_background);
			lenovoLayout
					.setBackgroundResource(android.R.drawable.list_selector_background);
		} else if (event.getAction() == MotionEvent.ACTION_UP) {
			phoneLayout.setBackgroundColor(0);
			sdcardLayout.setBackgroundColor(0);
			lenovoLayout.setBackgroundColor(0);
		} else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
			phoneLayout.setBackgroundColor(0);
			sdcardLayout.setBackgroundColor(0);
			lenovoLayout.setBackgroundColor(0);
		}
		return false;
	}

}
